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.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »