Java Reference
In-Depth Information
19
private
JTextField jtfMessage =
new
JTextField(
10
);
create text field
20
21
public static void
main(String[] args) {
22 GUIEventDemo frame =
new
GUIEventDemo();
23 frame.pack();
24 frame.setTitle(
"GUIEventDemo"
);
25 frame.setLocationRelativeTo(
null
);
// Center the frame
26 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 frame.setVisible(
true
);
28 }
29
30
public
GUIEventDemo() {
31 jlblMessage.setBorder(
new
LineBorder(Color.BLACK,
2
));
32 add(jlblMessage, BorderLayout.CENTER);
33
34
// Create a panel to hold check boxes
35 JPanel jpCheckBoxes =
new
JPanel();
36 jpCheckBoxes.setLayout(
new
GridLayout(
2
,
1
));
37 jpCheckBoxes.add(jchkBold);
38 jpCheckBoxes.add(jchkItalic);
39 add(jpCheckBoxes, BorderLayout.EAST);
40
41
// Create a panel to hold radio buttons
42 JPanel jpRadioButtons =
new
JPanel();
43 jpRadioButtons.setLayout(
new
GridLayout(
3
,
1
));
44 jpRadioButtons.add(jrbRed);
45 jpRadioButtons.add(jrbGreen);
46 jpRadioButtons.add(jrbBlue);
47 add(jpRadioButtons, BorderLayout.WEST);
48
49
// Create a radio-button group to group three buttons
50 ButtonGroup group =
new
ButtonGroup();
51 group.add(jrbRed);
52 group.add(jrbGreen);
53 group.add(jrbBlue);
54
55
// Set initial message color to blue
56 jrbBlue.setSelected(
true
);
57 jlblMessage.setForeground(Color.blue);
58
59
// Create a panel to hold label and text field
60 JPanel jpTextField =
new
JPanel();
61 jpTextField.setLayout(
new
BorderLayout(
5
,
0
));
62 jpTextField.add(
63
new
JLabel(
"Enter a new message"
), BorderLayout.WEST);
64 jpTextField.add(jtfMessage, BorderLayout.CENTER);
65 jtfMessage.setHorizontalAlignment(JTextField.RIGHT);
66 add(jpTextField, BorderLayout.NORTH);
67
68
// Set mnemonic keys for check boxes and radio buttons
69 jchkBold.setMnemonic(
'B'
);
70 jchkItalic.setMnemonic(
'I'
);
71 jrbRed.setMnemonic(
'E'
);
72 jrbGreen.setMnemonic(
'G'
);
73 jrbBlue.setMnemonic(
'U'
);
74
75
// Register listeners with check boxes
76 jchkBold.addActionListener(
new
ActionListener() {
77 @Override
78
create frame
pack frame
create UI
place label
panel for check boxes
panel for radio buttons
group buttons
panel for text field
set mnemonics
register listener
public void
actionPerformed(ActionEvent e) {