我的代码:
package run;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxModelTest extends JFrame {
private static final long serialVersionUID = 1L;
JComboBox<String> jc = new JComboBox<>(new MyComboBox());
JLabel jl = new JLabel("请选择产品类型:");
JTextField jt1 = new JTextField("aaa",10);
final JButton jb1=new JButton("清除");
JTextField jt2 = new JTextField("aaa",10);
final JButton jb2=new JButton("清除");
JTextField jt3 = new JTextField("aaa",10);
final JButton jb3=new JButton("清除");
final JButton jb4=new JButton("绑定IP");
public JComboBoxModelTest() {
setSize(new Dimension(800, 500));
setVisible(true);
setTitle("在窗口中设置下拉列表框");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(new FlowLayout(0));
cp.add(jl);
cp.add(jc);
cp.add(jt1);
cp.add(jb1);
cp.add(jt2);
cp.add(jb2);
cp.add(jt3);
cp.add(jb3);
cp.add(jb4);
jt1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO 自动生成方法存根
jt1.setText("触发事件");
}
});
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
jt1.setText("");
jt1.requestFocus();
}
});
jt2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO 自动生成方法存根
jt2.setText("触发事件");
}
});
jb2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
jt2.setText("");
jt2.requestFocus();
}
});
jt3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO 自动生成方法存根
jt3.setText("触发事件");
}
});
jb3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
jt3.setText("");
jt3.requestFocus();
}
});
}
public static void main(String[] args) {
new JComboBoxModelTest();
}
}
class MyComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {
private static final long serialVersionUID = 1L;
String selecteditem = null;
String[] test = { "A", "B", "C", "D" };
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;
}
public int getIndex() {
for (int i = 0; i < test.length; i++) {
if (test[i].equals(getSelectedItem()))
return i;
}
return 0;
}
}