@Thus far, our HelloJava example has contained itself in a single class. In fact, because of its simple nature, it has really just served as a single, large method. Although we have used a couple of objects to display our GUI message, our own code does not illustrate any object-oriented structure. Well, we’re going to correct that right now by adding a second class. To give us something to build on throughout this chapter, we’re going to take over the job of the JLabel class (bye bye, JLabel!) and replace it with our own graphical class: HelloComponent. Our HelloComponent class will start simple, just displaying our “Hello, Java!” message at a fixed position. We’ll add capabilities later. The code for our new class is very simple; we added just a few more lines:
import java.awt.*;
class HelloComponent extends JComponent {
public void paintComponent( Graphics g ) {
g.drawString( "Hello, Java!", 125, 95 );
}
}
You can add this text to the HelloJava.java file, or you can place it in its own file called
HelloComponent.java. If you put it in the same file, you must move the new import
statement to the top of the file, along with the other one. To use our new class in place
of the JLabel, simply replace the two lines referencing the label with:
frame.add( new HelloComponent() );
This time when you compile HelloJava.java, you will see two binary class files: Hello‐
Java.class and HelloComponent.class (regardless of how you arranged the source). Running
the code should look much like the JLabel version, but if you resize the window,
you’ll notice that our class does not automatically adjust to center the code.
So what have we done, and why have we gone to such lengths to insult the perfectly
good JLabel component? We’ve created our new HelloComponent class, extending a
generic graphical class called JComponent. To extend a class simply means to add functionality
to an existing class, creating a new one. We’ll get into that in the next section.
Here we have created a new kind of JComponent that contains a method called paint
Component(), which is responsible for drawing our message. Our paintComponent()
method takes one argument named (somewhat tersely) g, which is of type Graphics.
When the paintComponent() method is invoked, a Graphics object is assigned to g,
which we use in the body of the method. We’ll say more about paintComponent() and
the Graphics class in a moment. As for why, you’ll understand when we add all sorts of
new features to our new component later on.
0 comments:
Post a Comment