public class Test2 extends JFrame{
String[] test = new String[4];
String[] test2 ={"煞笔","白痴","智障","蠢货"};
static JButton button = new JButton("添加");
MyComboBox combo = new MyComboBox();
JComboBox jc = new JComboBox(combo);
public Test2(){
getContentPane().add(button,BorderLayout.SOUTH);
button.addActionListener(combo);
getContentPane().add(jc,BorderLayout.NORTH);
}
public static void main(String[] args) {
Test2 test1 = new Test2();
test1.setSize(400,300);
test1.setVisible(true);
}
class MyComboBox extends AbstractListModel implements ComboBoxModel,ActionListener{
String selecteditem = null;
int size=0;
public void actionPerformed(ActionEvent e) {
if(size<test.length){
test[size]=test2[size];
size++;
}
}
public Object getElementAt(int index){
System.out.println("index="+index);
return test[index];
}
public int getSize(){
return test.length;
}
public void setSelectedItem(Object item){
System.out.println("item="+item);
selecteditem = (String)item;
}
public Object getSelectedItem(){
return selecteditem;
}
}
}
这个Java程序创建了一个Swing应用,包含一个自定义的组合框`MyComboBox`,该组合框继承自`AbstractListModel`并实现了`ComboBoxModel`和`ActionListener`接口。当用户点击添加按钮时,会将预定义的字符串数组`test2`中的元素添加到`test`数组中,直到`test`数组填满。程序还展示了如何将自定义的组合框添加到窗口布局中。
74





