How do I determine if the menu of JComboBox is displayed?

This example show how to create an implementation of PopupMenuListener for listening to when the JComboBox menu is visible, invisible or cancelled.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import java.awt.*;

public class ComboBoxPopupMenuListener extends JFrame {
    public ComboBoxPopupMenuListener() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        Integer[] years = new Integer[] {2005, 2006, 2007, 2008, 2009, 2010};
        JComboBox<Integer> comboBox = new JComboBox<>(years);
        comboBox.setEditable(true);

        // Adds a PopupMenu listener which will listen to notification
        // messages from the popup portion of the combo box.
        comboBox.addPopupMenuListener(new PopupMenuListener() {
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes visible.
                System.out.println("PopupMenuWillBecomeVisible");
            }

            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes invisible
                System.out.println("PopupMenuWillBecomeInvisible");
            }

            public void popupMenuCanceled(PopupMenuEvent e) {
                // This method is called when the popup menu is canceled
                System.out.println("PopupMenuCanceled");
            }
        });

        getContentPane().add(comboBox);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxPopupMenuListener().setVisible(true);
            }
        });
    }
}

How do I add an action listener to JComboBox?

The code below shows you how to add an ActionListener to a JComboBox component. In the snippet we add a listener by calling the addActionListener() method and give an instance of ActionListener listener as an anonymous class (a class without a specified name) as the parameter.

The ActionListener interface contract said that we must implement the actionPerformed(ActionEvent e) method. This is the place where the event will be handled by our program.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ComboBoxActionListener extends JFrame {
    public ComboBoxActionListener() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        String[] names = new String[]{
                "James", "Joshua", "Matt", "John", "Paul"
        };
        JComboBox comboBox = new JComboBox<String>(names);
        comboBox.setEditable(true);

        // Create an ActionListener for the JComboBox component.
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // Get the source of the component, which is our combo
                // box.
                JComboBox comboBox = (JComboBox) event.getSource();

                // Print the selected items and the action command.
                Object selected = comboBox.getSelectedItem();
                System.out.println("Selected Item  = " + selected);
                String command = event.getActionCommand();
                System.out.println("Action Command = " + command);

                // Detect whether the action command is "comboBoxEdited"
                // or "comboBoxChanged"
                if ("comboBoxEdited".equals(command)) {
                    System.out.println("User has typed a string in " +
                            "the combo box.");
                } else if ("comboBoxChanged".equals(command)) {
                    System.out.println("User has selected an item " +
                            "from the combo box.");
                }
            }
        });
        getContentPane().add(comboBox);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxActionListener().setVisible(true);
            }
        });
    }
}

How do I listening for changes to the selected item in JComboBox?

This examples demonstrate the ItemListener to listen for changes to the selected item in the JComboBox component.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.*;

public class ComboBoxSelectionChange extends JFrame {
    public ComboBoxSelectionChange() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        String[] items = new String[] {"A", "B", "C", "D", "E", "F"};
        JComboBox<String> comboBox = new JComboBox<>(items);

        final JTextArea textArea = new JTextArea(5, 15);
        textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));

        // For listening to the changes of the selected items in the combo box
        // we need to add an ItemListener to the combo box component as shown
        // below.
        comboBox.addItemListener(new ItemListener() {
            // Listening if a new items of the combo box has been selected.
            public void itemStateChanged(ItemEvent event) {
                JComboBox comboBox = (JComboBox) event.getSource();

                // The item affected by the event.
                Object item = event.getItem();

                textArea.setText("Affected items: " + item.toString());

                if (event.getStateChange() == ItemEvent.SELECTED) {
                    textArea.setText(item.toString() + " selected.");
                }

                if (event.getStateChange() == ItemEvent.DESELECTED) {
                    textArea.setText(item.toString() + " deselected.");
                }
            }
        });

        getContentPane().add(comboBox);
        getContentPane().add(textArea);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxSelectionChange().setVisible(true);
            }
        });
    }
}

How do I change the number of visible items in JComboBox?

In this example you’ll see how we can change the default number of visible items in the combo box. By default it only show eight items at once and when the combo box has more items a scrollbar will be shown so we can scroll up and down in the combo box list.

If we want to change this value we can call the setMaximumRowCount(int count) of the JComboBox. Let’s see the following example for more details.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class ComboBoxMaximumRows extends JFrame {
    public ComboBoxMaximumRows() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Create some items for our JComboBox component. In this example we are
        // going to pass an array of string which are the name of the month.
        String[] months = {"January", "February", "March", "April", "Mei", "June",
            "July", "August", "September", "October", "November", "December"};

        // Create a month selection combo box.
        JComboBox comboBox = new JComboBox(months);

        // By default combo box will only shows eight items in the drop down. When
        // more that eight items are in the combo box a default scrollbar will be
        // shown. If we want to display more items we can change it by calling the
        // setMaximumRowCount() method.
        comboBox.setMaximumRowCount(12);

        getContentPane().add(comboBox);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxMaximumRows().setVisible(true);
            }
        });
    }
}

How do I add items and remove items from JComboBox?

This example demonstrate how to add an items into a specific position in the combo box list or at the end of the list using the insertItemAt(Object o, int index) and addItem(Object o) method. In the code we also learn how to remove one or all items from the list using removeItemAt(int index) method and removeAllItems() method of JComboBox.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ComboBoxAddRemoveItem extends JFrame {
    public ComboBoxAddRemoveItem() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        String[] items = new String[] {"Two", "Four", "Six", "Eight"};
        final JComboBox comboBox = new JComboBox(items);

        getContentPane().add(comboBox);

        JButton button1 = new JButton("Add One");
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Add item "One" at the beginning of the list.
                comboBox.insertItemAt("One", 0);
            }
        });
        JButton button2 = new JButton("Add Five and Nine");
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Add item Five on the third index and Nine at the end of the
                // list.
                comboBox.insertItemAt("Five", 3);
                comboBox.addItem("Nine");
            }
        });

        getContentPane().add(button1);
        getContentPane().add(button2);

        JButton remove1 = new JButton("Remove Eight and Last");
        remove1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Remove the Eight item and the last item from the list.
                comboBox.removeItemAt(5);
                comboBox.removeItemAt(comboBox.getItemCount() - 1);
            }
        });
        JButton remove2 = new JButton("Remove All");
        remove2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                comboBox.removeAllItems();
            }
        });

        getContentPane().add(remove1);
        getContentPane().add(remove2);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxAddRemoveItem().setVisible(true);
            }
        });
    }
}

How do I get items of JComboBox?

This example demonstrate the use of JComboBox‘s getItemCount() method and getItemAt(int index) to get the number of items inside the combo box and how to obtain each of them.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ComboBoxGetItems extends JFrame {
    public ComboBoxGetItems() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Create JComboBox with grade as the values;
        String[] items = new String[] {"A", "B", "C", "D", "E", "F"};
        final JComboBox<String> gradeCombo = new JComboBox<>(items);
        getContentPane().add(gradeCombo);

        JButton button = new JButton("Get Items");
        final JLabel label = new JLabel("Items count: ");

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Get the number of items in the combo box drop down. Iterate
                // from zero to the number of combo box items and get each item
                // of the specified index.
                //
                // In this example we just place the items inside a StringBuilder
                // and print it later on.
                int count = gradeCombo.getItemCount();
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < count; i++) {
                    builder.append(gradeCombo.getItemAt(i));
                    if (i < count - 1) {
                        builder.append(", ");
                    }
                }
                label.setText("Item count: " + count + "; ["
                    + builder.toString() + "]");
            }
        });

        getContentPane().add(button);
        getContentPane().add(label);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxGetItems().setVisible(true);
            }
        });
    }
}

How do I set and get the selected item in JComboBox?

The code below demonstrate how to set the selected item of JComboBox and then on how to get the value of the selected item. In this example we set the JComboBox component so that user can enter their own value.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ComboBoxSelectedItem extends JFrame {
    public ComboBoxSelectedItem() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Create a combo box with four items and set it to editable so that user can
        // enter their own value.
        final JComboBox<String> comboBox = new JComboBox<>(new String[] {"One", "Two", "Three", "Four"});
        comboBox.setEditable(true);
        getContentPane().add(comboBox);

        // Create two button that will set the selected item of the combo box. The
        // first button select "Two" and and second button select "Four".
        JButton button1 = new JButton("Set Two");
        getContentPane().add(button1);
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                comboBox.setSelectedItem("Two");
            }
        });

        JButton button2 = new JButton("Set Four");
        getContentPane().add(button2);
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                comboBox.setSelectedItem("Four");
            }
        });

        // Create a text field for displaying the selected item when we press the
        // Get Value button. When user enter their own value the selected item
        // returned is the string that entered by user.
        final JTextField textField = new JTextField("");
        textField.setPreferredSize(new Dimension(150, 20));

        JButton button3 = new JButton("Get Value");
        getContentPane().add(button3);
        getContentPane().add(textField);
        button3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText((String) comboBox.getSelectedItem());
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxSelectedItem().setVisible(true);
            }
        });
    }
}

How do I create JComboBox?

A JComboBox allows user to select a value from a drop down items available in the component. When the combo box set to editable user can enter their own value by typing it directly in the combo box editor. The code below demonstrate how you can create a simple combo box component.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class ComboBoxCreate extends JFrame {
    public ComboBoxCreate() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        JLabel label1 = new JLabel("Month  :");
        JLabel label2 = new JLabel("Number :");

        // Create some items for our JComboBox component. In this example we are
        // going to pass an array of string which are the name of the month.
        String[] months = {"January", "February", "March", "April", "Mei", "June",
            "July", "August", "September", "October", "November", "December"};

        // Create a month selection combo box.
        JComboBox<String> comboBox = new JComboBox<>(months);

        // Below, instead of passing directly a string array we create a ComboBoxModel
        // as the combo box data model. Using a model we can for example define the
        // selected item of the combo box.
        ComboBoxModel<String> model =
            new DefaultComboBoxModel<>(new String[] {"1", "2", "3", "4", "5"});
        model.setSelectedItem("3");
        JComboBox<String> numberComboBox = new JComboBox<>(model);

        // We also set the combo box to be editable so that user can enter their own
        // value other that those defined in the combo box.
        numberComboBox.setEditable(true);

        // Add the entire component to out frame content pane.
        getContentPane().add(label1);
        getContentPane().add(comboBox);

        getContentPane().add(label2);
        getContentPane().add(numberComboBox);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxCreate().setVisible(true);
            }
        });
    }
}