import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JComboBoxModelTest extends JFrame {
JComboBox<String> jc = new JComboBox<>(new MyComboBox());
JLabel jl = new JLabel("动物:");
public JComboBoxModelTest() {
this.setSize(300, 300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle("Demo for JComboBox");
this.setLayout(new FlowLayout());
this.add(jl);
this.add(jc);
jc.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(jc.getSelectedItem());
}
});
this.setVisible(true);
}
public static void main(String[] args) {
new JComboBoxModelTest();
}
}
class MyComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {
String selectedItem = null;
String[] test = {"猫", "狗", "牛", "羊"};
public String getElementAt(int index) {
return test[index];
}
public int getSize(){
return test.length;
}
public void setSelectedItem(Object item) {
selectedItem = (String)item;
}
public Object getSelectedItem() {
return selectedItem;
}
}