Java Reference
In-Depth Information
12.4 Frames
A frame is a window for holding other GUI components.
Key
Point
To create a user interface, you need to create either a frame or an applet to hold the user-
interface components. This section introduces frames. Creating Java applets will be intro-
duced in Chapter 18.
12.4.1 Creating a Frame
To create a frame, use the JFrame class, as shown in Figure 12.2.
javax.swing.JFrame
+JFrame()
+JFrame(title: String)
+setSize(width: int, height: int): void
+setLocation(x: int, y: int): void
+setVisible(visible: boolean): void
+setDefaultCloseOperation(mode: int): void
+setLocationRelativeTo(c: Component):
Creates a default frame with no title.
Creates a frame with the specified title.
Sets the size of the frame.
Sets the upper-left-corner location of the frame.
Sets true to display the frame.
Specifies the operation when the frame is closed.
Sets the location of the frame relative to the specified component.
If the component is null, the frame is centered on the screen.
void
Automatically sets the frame size to hold the components in the
frame.
+pack(): void
F IGURE 12.2
The JFrame class is used to create a window for displaying GUI components.
The program in Listing 12.1 creates a frame.
L ISTING 12.1 MyFrame.java
1
import javax.swing.JFrame;
import package
2
3 public class MyFrame {
4 public static void main(String[] args) {
5 JFrame frame = new JFrame( "MyFrame" ); // Create a frame
6 frame.setSize( 400 , 300 ); // Set the frame size
7 // Center a frame
8 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9 frame.setVisible( true ); // Display the frame
10 }
11 }
create frame
set size
center frame
close upon exit
display the frame
frame.setLocationRelativeTo( null );
The frame is not displayed until the frame.setVisible(true) method is invoked.
frame.setSize(400, 300) specifies that the frame is 400 pixels wide and 300 pixels
high. If the setSize method is not used, the frame will be sized to display just the title bar.
Since the setSize and setVisible methods are both defined in the Component class, they
are inherited by the JFrame class. Later you will see that these methods are also useful in
many other subclasses of Component .
When you run the MyFrame program, a window will be displayed on the screen (see
Figure 12.3a).
Invoking setLocationRelativeTo(null) (line 7) centers the frame on the screen.
Invoking setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) (line 8) tells the pro-
gram to terminate when the frame is closed. If this statement is not used, the program does not
terminate when the frame is closed. In that case, you have to stop the program by pressing
Ctrl+C at the DOS prompt window in Windows or stop the process by using the kill command
 
 
Search WWH ::




Custom Search