Java Reference
In-Depth Information
11
12
13 frame2.setTitle( "Window 2" );
14 frame2.setSize( 200 , 150 );
15 frame2.setLocation( 410 , 100 );
16 frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17 frame2.setVisible( true );
18 }
19 }
JFrame frame2 = new JFrame();
create an object
invoke a method
This program creates two objects of the JFrame class (lines 5, 12) and then uses the methods
setTitle , setSize , setLocation , setDefaultCloseOperation , and setVisible to
set the properties of the objects. The setTitle method sets a title for the window (lines 6,
13). The setSize method sets the window's width and height (lines 7, 14). The
setLocation method specifies the location of the window's upper-left corner (lines 8, 15).
The setDefaultCloseOperation method terminates the program when the frame is
closed (lines 9, 16). The setVisible method displays the window.
You can add graphical user interface components, such as buttons, labels, text fields, check
boxes, and combo boxes to the window. The components are defined using classes. Listing
8.6 gives an example of creating a graphical user interface, as shown in Figure 8.1.
L ISTING 8.6 GUIComponents.java
1
import javax.swing.*;
VideoNote
Use classes
2
3 public class GUIComponents {
4 public static void main(String[] args) {
5 // Create a button with text OK
6 JButton jbtOK = new JButton( "OK" );
7
8 // Create a button with text Cancel
9 JButton jbtCancel = new JButton( "Cancel" );
10
11 // Create a label with text "Enter your name: "
12 JLabel jlblName = new JLabel( "Enter your name: " );
13
14 // Create a text field with text "Type Name Here"
15 JTextField jtfName = new JTextField( "Type Name Here" );
16
17 // Create a check box with text Bold
18 JCheckBox jchkBold = new JCheckBox( "Bold" );
19
20 // Create a check box with text Italic
21 JCheckBox jchkItalic = new JCheckBox( "Italic" );
22
23 // Create a radio button with text Red
24 JRadioButton jrbRed = new JRadioButton( "Red" );
25
26 // Create a radio button with text Yellow
27 JRadioButton jrbYellow = new JRadioButton( "Yellow" );
28
29 // Create a combo box with several choices
30 JComboBox jcboColor = new JComboBox( new String[]{ "Freshman" ,
31
create a button
create a button
create a label
create a text field
create a check box
create a check box
create a radio button
create a radio button
create a combo box
"Sophomore" , "Junior" , "Senior" });
32
33 // Create a panel to group components
34 JPanel panel = new JPanel();
35 panel.add(jbtOK); // Add the OK button to the panel
36 panel.add(jbtCancel); // Add the Cancel button to the panel
create a panel
add to panel
 
Search WWH ::




Custom Search