Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Using Components 171

One way to make use of a frame in a Java application is to make the appli-
cation a subclass of JFrame. Your program inherits the behavior it needs to
function as a frame. The following statements create a subclass of JFrame:


importjavax.swing.*;


public classMainFrame extendsJFrame {
publicMainFrame() {
// set up the frame
}
}


This class creates a frame but doesn’t set it up completely. In the frame’s
constructor, you must do several things when creating a frame:


. Call a constructor of the superclass, JFrame.
. Set up the title of the frame.
. Set up the size of the frame.
. Set the frame’s look and feel.
. Define what happens when the frame is closed by a user.


You also must make the frame visible, unless for some reason it should not
be displayed when the application begins running.


Most of these things can be handled in the frame’s constructor. The first
thing the method must contain is a call to one of the constructors of
JFrame, using the superstatement. Here’s an example:


super();


The preceding statement calls theJFrameconstructor with no arguments.
You also can call it with the title of your frame as an argument:


super(“Main Frame”);


This sets the title of the frame, which appears in the title bar along the top
edge, to the specified string. In this example, the text greeting “Main
Frame” appears.


If you don’t set up a title in this way, you can call the frame’s setTitle()
method with a string as an argument:


setTitle(“Main Frame”);

Free download pdf