首先写数据模型
//列表框
class ListModelExample extends AbstractListModel{
String values[]={"张三","李四","王五","周六","赵七","孙八"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
}
//组合框
class ComboModelExample extends ListModelExample implements ComboBoxModel{
private Object item;
public void setSelectedItem(Object anItem){
item=anItem;
}
public Object getSelectedItem() {
return item;
}
}
直接去实现ComboBoxModel接口要写多个方法,最好是运用继承.
JListlist=new JList(new ListModelExample());
list.setVisibleRowCount(4);
JScrollPanepane=new JScrollPane();
pane.setViewportView(list);
this.add(pane);
JComboBoxcombobox=new JComboBox(new ComboModelExample());
this.add(combobox);
然后将它们用到JList和JComboBox的构造函数中.
也可先不指定数据,以后再添加
private JComboBoxcombo=new JComboBox();
combo.addItem("TOP");
combo.addItem("LEFT");
combo.addItem("RIGHT");
事件监听:
combo.addItemListener(new ItemListener() {
public voiditemStateChanged(ItemEvent e) {
//状态改变,分变为被选和变为不被选
if(e.getStateChange()==ItemEvent.SELECTED){
String s=(String) e.getItem();
if(s.equals("TOP"))
tp.setTabPlacement(JTabbedPane.TOP) }
}
});