Java Swing Tutorial - Java Swing JComboBox








A JComboBox<E> is a Swing component that allows us make one selection from a list of choices.

JComboBox can have an editable field and we can type a new choice value.

The type parameter E is the type of the elements it contains.

We can create a JComboBox by passing the list of choices in one of its constructors.

The following code uses an array of String as the list of choices.

String[] sList = new String[]{"Spring", "Summer",  "Fall",  "Winter"}; 
JComboBox<String> seasons = new JComboBox<>(sList);

The following code uses a Vector of String as the list of choices

Vector<String> myList  = new Vector<>(4); 
myList.add("Spring");
myList.add("Summer"); 
myList.add("Fall"); 
myList.add("Winter");
JComboBox<String> seasons2 = new JComboBox<>(myList);

The following table lists commonly Used Methods of the JComboBox class.

IDMethod/Description
1void addItem(E item)
Adds an item to the list. The toString() method on the added object is called and the returned string is displayed.
2E getItemAt(int index)
Returns the item at the specified index from the list.
3int getItemCount()
Returns the number of items in the list of choices.
4int getSelectedIndex()
Returns the index of the selected item. It returns -1, if the selected item is not in the list.
5Object getSelectedItem()
Returns the currently selected item. Returns null if there is no selection.
6void insertItemAt(E item, int index)
Inserts the specified item at the specified index in the list.
7boolean isEditable()
Returns true if the JComboBox is editable. Otherwise, it returns false. By default, a JComboBox is non-editable.
8void removeAllItems()
Removes all items from the list.
9void removeItem(Object item)
Removes the specified item from the list.
10void removeItemAt(int index)
Removes the item at the specified index.
11void setEditable(boolean editable)
If the specified editable argument is true, the JComboBox is editable. Otherwise, it is non-editable.
12void setSelectedIndex(int index)
Selects the item at the specified index in the list. If the specified index is -1, it clears the selection.
13void setSelectedItem(Object item)
Selects the item in the field. If the specified item exists in the list, it is always selected.




Selection Event

To handle selected or deselected events in the JComboBox, add an item listener to it. An item listener is notified whenever an item is selected or deselected.

The following code shows how to add an item listener to a JComboBox.

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ItemEvent;
// w  ww  .  j ava  2s  .com
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame {
  public Main() {
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    String[] sList = new String[] { "Spring", "Summer", "Fall", "Winter" };
    JComboBox<String> seasons = new JComboBox<>(sList);

    seasons.addItemListener((ItemEvent e) -> {
      Object item = e.getItem();
      if (e.getStateChange() == ItemEvent.SELECTED) {
        // Item has been selected
        System.out.println(item + "  has  been  selected");
      } else if (e.getStateChange() == ItemEvent.DESELECTED) {
        // Item has been deselected
        System.out.println(item + "  has  been  deselected");
      }
    });

    Container contentPane = this.getContentPane();
    contentPane.add(seasons, BorderLayout.CENTER);
  }

  public static void main(String[] args) {
    Main bf = new Main();
    bf.pack();
    bf.setVisible(true);
  }
}




ActionListener

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*  w w w  .j  a  v  a2s .c  o m*/
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame {
  JComboBox combo = new JComboBox();

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    combo.addItem("A");
    combo.addItem("H");
    combo.addItem("P");
    combo.setEditable(true);
    System.out.println("#items=" + combo.getItemCount());

    combo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Selected index=" + combo.getSelectedIndex()
            + " Selected item=" + combo.getSelectedItem());
      }
    });

    getContentPane().add(combo);
    pack();
    setVisible(true);
  }

  public static void main(String arg[]) {
    new Main();
  }
}

Sharing the Data Model between two JComboBoxes

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//  w w  w . java  2  s  .  com
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SharedDataBetweenComboBoxSample {
  public static void main(String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

    final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);

    JFrame frame = new JFrame("Shared Data");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    JComboBox comboBox1 = new JComboBox(model);
    comboBox1.setEditable(true);

    JComboBox comboBox2 = new JComboBox(model);
    comboBox2.setEditable(true);
    panel.add(comboBox1);
    panel.add(comboBox2);
    frame.add(panel, BorderLayout.NORTH);

    JButton button = new JButton("Add");
    frame.add(button, BorderLayout.SOUTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.addElement("New Added");
      }
    };
    button.addActionListener(actionListener);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

Listening to Keyboard Events with a KeySelectionManager

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//  www .jav  a  2s.  c  om
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class SelectingComboSample {

  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F" };
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComboBox comboBox = new JComboBox(labels);
    frame.add(comboBox, BorderLayout.SOUTH);

    JComboBox.KeySelectionManager manager =
      new JComboBox.KeySelectionManager() {
        public int selectionForKey(char aKey, ComboBoxModel aModel) {
          System.out.println(aKey);
          return -1;
        }
      };
    comboBox.setKeySelectionManager(manager);

    frame.setSize(400, 200);
    frame.setVisible(true);
  }
}

A Color Combo Box Editor

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from w  ww.j  a  v a  2 s. c o  m
import javax.swing.ComboBoxEditor;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.EventListenerList;

class ColorComboBoxEditor implements ComboBoxEditor {
  final protected JButton editor;

  protected EventListenerList listenerList = new EventListenerList();

  public ColorComboBoxEditor(Color initialColor) {
    editor = new JButton("");
    editor.setBackground(initialColor);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Color currentBackground = editor.getBackground();
        Color color = JColorChooser.showDialog(editor, "Color Chooser", currentBackground);
        if ((color != null) && (currentBackground != color)) {
          editor.setBackground(color);
          fireActionEvent(color);
        }
      }
    };
    editor.addActionListener(actionListener);
  }

  public void addActionListener(ActionListener l) {
    listenerList.add(ActionListener.class, l);
  }

  public Component getEditorComponent() {
    return editor;
  }

  public Object getItem() {
    return editor.getBackground();
  }

  public void removeActionListener(ActionListener l) {
    listenerList.remove(ActionListener.class, l);
  }

  public void selectAll() {
    // Ignore
  }

  public void setItem(Object newValue) {
    if (newValue instanceof Color) {
      Color color = (Color) newValue;
      editor.setBackground(color);
    } else {
      try {
        Color color = Color.decode(newValue.toString());
        editor.setBackground(color);
      } catch (NumberFormatException e) {
      }
    }
  }

  protected void fireActionEvent(Color color) {
    Object listeners[] = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == ActionListener.class) {
        ActionEvent actionEvent = new ActionEvent(editor, ActionEvent.ACTION_PERFORMED, color
            .toString());
        ((ActionListener) listeners[i + 1]).actionPerformed(actionEvent);
      }
    }
  }
}

public class Main {
  public static void main(String args[]) {
    Color colors[] = { Color.RED, Color.BLUE, Color.BLACK, Color.WHITE };
    JFrame frame = new JFrame("Editable JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JComboBox comboBox = new JComboBox(colors);
    comboBox.setEditable(true);
    comboBox.setEditor(new ColorComboBoxEditor(Color.RED));
    frame.add(comboBox, BorderLayout.NORTH);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

Combobox cell renderer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
//from  w  w  w  .j  av a 2s.c o m
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

class ComplexCellRenderer implements ListCellRenderer {
  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();

  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    Font theFont = null;
    Color theForeground = null;
    Icon theIcon = null;
    String theText = null;

    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
        isSelected, cellHasFocus);

    if (value instanceof Object[]) {
      Object values[] = (Object[]) value;
      theFont = (Font) values[0];
      theForeground = (Color) values[1];
      theIcon = (Icon) values[2];
      theText = (String) values[3];
    } else {
      theFont = list.getFont();
      theForeground = list.getForeground();
      theText = "";
    }
    if (!isSelected) {
      renderer.setForeground(theForeground);
    }
    if (theIcon != null) {
      renderer.setIcon(theIcon);
    }
    renderer.setText(theText);
    renderer.setFont(theFont);
    return renderer;
  }
}

public class Main {
  public static void main(String args[]) {
    Object elements[][] = {
        { new Font("Helvetica", Font.PLAIN, 20), Color.RED, new MyIcon(), "A" },
        { new Font("TimesRoman", Font.BOLD, 14), Color.BLUE, new MyIcon(), "A" },
        { new Font("Courier", Font.ITALIC, 18), Color.GREEN, new MyIcon(), "A" },
        { new Font("Helvetica", Font.BOLD | Font.ITALIC, 12), Color.GRAY, new MyIcon(), "A" },
        { new Font("TimesRoman", Font.PLAIN, 32), Color.PINK, new MyIcon(), "A" },
        { new Font("Courier", Font.BOLD, 16), Color.YELLOW, new MyIcon(), "A" },
        { new Font("Helvetica", Font.ITALIC, 8), Color.DARK_GRAY, new MyIcon(), "A" } };

    JFrame frame = new JFrame("Complex Renderer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ListCellRenderer renderer = new ComplexCellRenderer();
    JComboBox comboBox = new JComboBox(elements);
    comboBox.setRenderer(renderer);
    frame.add(comboBox, BorderLayout.NORTH);
    
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

class MyIcon implements Icon {

  public MyIcon() {
  }

  public int getIconHeight() {
    return 20;
  }

  public int getIconWidth() {
    return 20;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(Color.RED);
    g.drawRect(0, 0, 25, 25);
  }
}