Make JComboBox to use the Custom Model in Java

Description

The following code shows how to make JComboBox to use the Custom Model.

Example


 /*  w ww  .  j a va  2  s  .  c om*/
    
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;

class MyComboBoxModel extends AbstractListModel implements ComboBoxModel {
  String[] ComputerComps = { "Monitor", "Key Board", "Mouse", "Joy Stick", "Modem", "CD ROM",
      "RAM Chip", "Diskette" };

  String selection = null;

  public Object getElementAt(int index) {
    return ComputerComps[index];
  }

  public int getSize() {
    return ComputerComps.length;
  }

  public void setSelectedItem(Object anItem) {
    selection = (String) anItem; // to select and register an
  } // item from the pull-down list

  // Methods implemented from the interface ComboBoxModel
  public Object getSelectedItem() {
    return selection; // to add the selection to the combo box
  }
}

public class Main {

  public static void main(String[] a){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComboBox cbox = new JComboBox(new MyComboBoxModel());  
    cbox.setMaximumRowCount(5);   
    frame.add(cbox);   
    
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Make JComboBox to use the Custom Model 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