In this tutorial

You will learn how to...
  • How to create a JComboBox.
  • How to find what the current selection is.
  • How to add an ItemListener to it.

JComboBox - Part 1

The JComboBox is a very handy drop-down menu widget that lets you select one option from a list of things.
Let's bring back the 'random coloured squares' example we've used before and modify it to demonstrate how a JComboBox works and how you can implement it in the code.

This time we will go straight ahead and make the GUI react to the changes of the ComboBox. The JComboBox uses the ActionListener (just the same as JButton).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;

public class ComboBoxExample implements  ActionListener{

    JComboBox colorChooser;
    JPanel redBox, blueBox, greenBox, yellowBox;

    public JPanel createContentPane (){
        
        JPanel totalGUI = new JPanel();

        // To create a JComboBox, we need to pass in an array of Strings.
        // This gives the ComboBox the list of selections you can make.

        String colors[] = {"Red", "Blue", "Green", "Yellow"};
        
        colorChooser = new JComboBox(colors);
        colorChooser.setSelectedIndex(1);
        colorChooser.addActionListener(this);
        
        // Now we create a simple JPanel that displays our four coloured boxes.

        JPanel boxPanel = new JPanel(new GridLayout(2, 2, 20, 20));

        redBox = createSquareJPanel(Color.red, 50);
        blueBox = createSquareJPanel(Color.blue, 50);
        greenBox = createSquareJPanel(Color.green, 50);
        yellowBox = createSquareJPanel(Color.yellow, 50);

        // This sets all bar the blue box to be hidden.

        redBox.setVisible(false);
        greenBox.setVisible(false);
        yellowBox.setVisible(false);

        boxPanel.add(redBox);
        boxPanel.add(blueBox);
        boxPanel.add(greenBox);
        boxPanel.add(yellowBox);

        // This sets the widgets on the screen to be layed out in a
        // top to bottom fashion with spacers inbetween.
        
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
        
        bottomPanel.add(Box.createRigidArea(new Dimension(0,10)));
        bottomPanel.add(colorChooser);
        bottomPanel.add(Box.createRigidArea(new Dimension(0,20)));
        bottomPanel.add(boxPanel);
        bottomPanel.add(Box.createRigidArea(new Dimension(0,10)));
        
        totalGUI.add(bottomPanel);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // In this method, we create a square JPanel of a colour and set size
    // specified by the arguments.

    private JPanel createSquareJPanel(Color color, int size) {
        JPanel tempPanel = new JPanel();
        tempPanel.setBackground(color);
        tempPanel.setMinimumSize(new Dimension(size, size));
        tempPanel.setMaximumSize(new Dimension(size, size));
        tempPanel.setPreferredSize(new Dimension(size, size));
        return tempPanel;
    }

    // This actionPerformed simply takes sets the visibility of each
    // coloured box depending on what is selected on the combo box.

    public void actionPerformed(ActionEvent e) {

        int temp;
        
        if(e.getSource() == colorChooser)
        {
            temp = colorChooser.getSelectedIndex();
            
            switch(temp){
            case 0: 
                redBox.setVisible(true);
                blueBox.setVisible(false);
                greenBox.setVisible(false);
                yellowBox.setVisible(false);
                break;
            case 1:
                redBox.setVisible(false);
                blueBox.setVisible(true);
                greenBox.setVisible(false);
                yellowBox.setVisible(false);
                break;
            case 2:
                redBox.setVisible(false);
                blueBox.setVisible(false);
                greenBox.setVisible(true);
                yellowBox.setVisible(false);
                break;
            case 3:
                redBox.setVisible(false);
                blueBox.setVisible(false);
                greenBox.setVisible(false);
                yellowBox.setVisible(true);
                break;
            }
        }
    }

    private static void createAndShowGUI() {
    
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JComboBox [=]");

        ComboBoxExample demo = new ComboBoxExample();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
Picture of a Combobox

There is not much code in this example you have not seen before apart from the JComboBox (which is kind of the point!).
Please compile and run this code, as it really does help you see how this stuff works. And by all means play around and wreck it, there will always be a working version here!

We first create a String array with the options you want to choose from in the JComboBox.
18
        String colors[] = {"Red", "Blue", "Green", "Yellow"};
Then, we instantiate the JComboBox and pass in the String array as an argument.
20
        colorChooser = new JComboBox(colors);
Finally we set the starting value to "Blue", which is index 1.
21
        colorChooser.setSelectedIndex(1);
And squeeze an ActionListener on at the end.
22
        colorChooser.addActionListener(this);
Easy peasy. By this stage, none of that should really be a surprise to you!

The action event provides us with the index of the number that has been selected. We get this information by using the method .getSelectedIndex(). This way we can determine what has been chosen on the menu and make the GUI change.
We use a switch statement to provide us with the answer.
83
            temp = colorChooser.getSelectedIndex();

Exercises

For this exercise, you are you re-develop this program so that the coloured JPanels are in an array. This way, when we get the index of the JComboBox that is selected, we can set the JPanel in the array to visible and the others not using a for loop, rather than a large switch.

Hint for Exercise #1

Exercise #1 Example Code

Questions

Can you conquer the ComboBox?

Question 1. How do we pass options into the JComboBox?

  • a) Pass in an array of Strings as an argument.
  • b) Pass in all the options as individual String arguments.
  • c) Pass in a text file as an argument

Question 2. How do we determine which option has been selected?

  • a) .getSelectedOption()
  • b) .getSelectedIndex()
  • c) .getSelectedString()




Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict