Java Swing How to - Make JComboBox editable for other value








Question

We would like to know how to make JComboBox editable for other value.

Answer

import java.awt.Dimension;
import java.awt.FlowLayout;
/*from w w  w.j a  v  a2 s .c om*/
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    Object[] items = new Object[] { "Dog", "Cat", "Other" };
    DefaultComboBoxModel dcbm = new DefaultComboBoxModel(items);
    JComboBox comboBox = new JComboBox(dcbm);
    comboBox.setPreferredSize(new Dimension(200, 20));
    comboBox.addItemListener(e -> {
        Object selectedItem = comboBox.getSelectedItem();
        boolean editable = selectedItem instanceof String
            && ((String) selectedItem).equals("Other");
        comboBox.setEditable(editable);
    });
    comboBox.getEditor().addActionListener(e -> {
      Object newItem = comboBox.getEditor().getItem();
      DefaultComboBoxModel d = (DefaultComboBoxModel) comboBox.getModel();
      d.addElement(newItem);
      d.setSelectedItem(newItem);

    });

    JPanel content = new JPanel(new FlowLayout());
    content.add(new JLabel("Test:"));
    content.add(comboBox);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(content);
    frame.pack();
    frame.setVisible(true);
  }
}