Java ComboBoxModel .setSelectedItem (Object anItem)
Syntax
ComboBoxModel.setSelectedItem(Object anItem) has the following syntax.
void setSelectedItem(Object anItem)
Example
In the following code shows how to use ComboBoxModel.setSelectedItem(Object anItem) method.
/*from w w w . j a v a 2 s . c o m*/
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Collection;
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<Object> col = System.getProperties().values();
ArrayList<Object> arrayList = new ArrayList<Object>(col);
ArrayListComboBoxModel model = new ArrayListComboBoxModel(arrayList);
JComboBox comboBox = new JComboBox(model);
frame.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);
}
}
Home »
Java Tutorial »
javax.swing »
Java Tutorial »
javax.swing »