JFrame Class
Package: javax.swing
The top-level component of most Swing-based applications is a “frame” and is defined by the JFrame
class. By itself, a frame doesn’t do much, but to do anything else in Swing, you must first create a frame. Figure 5-6 shows a frame that does nothing but display the message Hello,
World!
in its title bar.
Figure 5-6
Constructors
Constructor |
Description |
|
Creates a new frame with no title |
|
Creates a new frame with the specified title |
Methods
Method |
Description |
|
Adds the specified component to the frame. |
|
Gets the menu for this frame. |
|
Adjusts the size of the frame to fit the components you added to it. |
|
Removes the specified component from the frame. |
|
Sets the action taken when the user closes the frame. You should almost always specify |
|
Sets the icon displayed when the frame is minimized. |
|
Sets the layout manager used to control how components are arranged when the frame is displayed. The default is the |
|
Sets the |
|
Centers the frame onscreen if the parameter is |
|
Sets whether the size of the frame can be changed by the user. The default setting is |
|
Sets the size of the frame to the specified width and height. |
|
Sets the menu for this frame. |
At minimum, you want to set a title for a new frame, set the frame’s size large enough for the user to see any components you add to it (by default, the frame is 0 pixels wide and 0 pixels high, so it isn’t very useful), and call the setVisible
method to make the frame visible. Here’s one way to do that:
JFrame frame = new JFrame(“This is the title”);
frame.setSize(350, 260);
frame.setVisible(true);
It’s more common to create a class that extends the JFrame
class. Then you can call these methods in the constructor. For example:
import javax.swing.*;
public class HelloFrame extends JFrame
{
public static void main(String[] args)
{
new HelloFrame();
}
public HelloFrame()
{
this.setSize(200,100);
this.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
this.setTitle(“Hello World!”);
this.setVisible(true);
}
}
The preceding program is what I used to create the frame shown in Figure 5-6.