Create ArrayList based combobox model for JComboBox in Java

Description

The following code shows how to create ArrayList based combobox model for JComboBox.

Example


import java.awt.BorderLayout;
import java.awt.Container;
import java.util.ArrayList;
import java.util.Collection;
//w w w  .  ja  v  a  2s  .co  m
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("ArrayListComboBoxModel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Collection col = System.getProperties().values();
    ArrayList arrayList = new ArrayList(col);
    ArrayListComboBoxModel model = new ArrayListComboBoxModel(arrayList);

    JComboBox comboBox = new JComboBox(model);

    Container contentPane = frame.getContentPane();
    contentPane.add(comboBox, BorderLayout.NORTH);
    frame.setSize(300, 225);
    frame.setVisible(true);
  }
}

class ArrayListComboBoxModel extends AbstractListModel implements ComboBoxModel {
  private Object selectedItem;

  private ArrayList anArrayList;

  public ArrayListComboBoxModel(ArrayList arrayList) {
    anArrayList = arrayList;
  }

  public Object getSelectedItem() {
    return selectedItem;
  }

  public void setSelectedItem(Object newValue) {
    selectedItem = newValue;
  }

  public int getSize() {
    return anArrayList.size();
  }

  public Object getElementAt(int i) {
    return anArrayList.get(i);
  }

}

The code above generates the following result.

Create ArrayList based combobox model for JComboBox in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer