Java Reference
In-Depth Information
class JComponent . JComboBox is a generic class, like the class ArrayList (Chapter 7). When
you create a JComboBox , you specify the type of the objects that it manages—the JCombo-
Box then displays a String representation of each object.
1
// Fig. 12.21: ComboBoxFrame.java
2
// JComboBox that displays a list of image names.
3
import java.awt.FlowLayout;
4
import java.awt.event.ItemListener;
5
import java.awt.event.ItemEvent;
6
import javax.swing.JFrame;
7
import javax.swing.JLabel;
8
import javax.swing.JComboBox;
9
import javax.swing.Icon;
10
import javax.swing.ImageIcon;
11
12
public class ComboBoxFrame extends JFrame
13
{
14
private final JComboBox<String> imagesJComboBox; // holds icon names
15
private final JLabel label; // displays selected icon
16
17
private static final String[] names =
18
{ "bug1.gif" , "bug2.gif" , "travelbug.gif" , "buganim.gif" };
19
private final Icon[] icons = {
20
new ImageIcon(getClass().getResource(names[ 0 ])),
21
new ImageIcon(getClass().getResource(names[ 1 ])),
22
new ImageIcon(getClass().getResource(names[ 2 ])),
23
new ImageIcon(getClass().getResource(names[ 3 ]))};
24
25
// ComboBoxFrame constructor adds JComboBox to JFrame
26
public ComboBoxFrame()
27
{
28
super ( "Testing JComboBox") ;
29
setLayout( new FlowLayout()); // set frame layout
30
31
imagesJComboBox = new JComboBox<String>(names); // set up JComboBox
imagesJComboBox.setMaximumRowCount( 3 ); // display three rows
32
33
34
imagesJComboBox.addItemListener(
new ItemListener() // anonymous inner class
{
// handle JComboBox event
@Override
public void itemStateChanged(ItemEvent event)
{
// determine whether item selected
if (event.getStateChange() == ItemEvent.SELECTED )
label.setIcon(icons[
imagesJComboBox.getSelectedIndex()]);
}
} // end anonymous inner class
); // end call to addItemListener
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Fig. 12.21 | JComboBox that displays a list of image names. (Part 1 of 2.)
 
Search WWH ::




Custom Search