我的JComboBox,想像 Button.doClick()那样触发,代码应该是怎么写
我试图用
firePropertyChange()但不知道应该改变什么属性对刚添加了一项的JComboBox用setSelectedIndex(0)方法也会出错

解决方案 »

  1.   

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;public class TestMain extends JFrame {
    private MyComboBox box = null; public TestMain() {
    super("窗口");
    JButton a = new JButton("触发按钮");
    JPanel pane = new JPanel();
    String [] arr = {"aaaaa", "bbbbb", "ccccc"};

    box = new MyComboBox(arr);
    box.setEditable(true);
    pane.add(box);
    pane.add(a);

    box.addItemListener(new ItemListener(){
    public void itemStateChanged(ItemEvent e) {
    System.out.println(e.getItem());
    }});

    a.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    box.select(new ItemEvent(box, ItemEvent.ITEM_LAST, box.getSelectedItem(), ItemEvent.SELECTED));
    }});

    this.getContentPane().add(pane);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(300, 200);
    this.setVisible(true);
    }

    public static void main(String[] args) {
    new TestMain();
    }}
    class MyComboBox extends JComboBox{
    public MyComboBox(Object [] o) {
    super(o);
    }
    public void select(ItemEvent ie){
    this.fireItemStateChanged(ie);
    }
    }
      

  2.   

    也是个办法,为了使用JComboBox的受保护的fireItemStateChanged(ItemEvent)必须继承自JComboBox
      

  3.   

    可以不用继承,用反射就行了
    for example
    public void eventTest() {
          try {
              Class cls = JComboBox.class;
              Method method = cls.getDeclaredMethod("fireItemStateChanged", new Class[]{ItemEvent.class});
              method.setAccessible(true);
              JComboBox cmb = new JComboBox(new String[]{"aa", "bb"});
              ItemEvent event = new ItemEvent(cmb, 0, "aa", ItemEvent.SELECTED);
              method.invoke(cmb, new Object[]{event}); //触发ItemEvent事件
          } catch (Throwable e) {
              e.printStackTrace();
          }
      }