我用如下代码创建了下拉框:JComboBox choice = new JComboBox(); public void addGUI() { choice.addItem("1");
choice.addItem("2");
choice.addItem("3");
choice.addItem("4");
choice.addItem("5");
choice.addItem("6"); p1.add(normal);
p1.add(user);
p1.add(startSound);
p1.add(closeSound);
p1.add(close);
p1.add(choice); this.add(p1);
}现在已经可以得到具有从1到6的下拉框了,但我不知道如何获取下拉框的值。
我将下列代码写入我的监听器当中,可是不奏效:public void itemStateChanged(final ItemEvent e) {
System.out.println(e.getItem());
System.out.println(choice.getSelectedItem().toString());
}不知是何原因。请大家指教!

解决方案 »

  1.   

      jComboBox1 = new javax.swing.JComboBox();        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            jComboBox1.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    jComboBox1ItemStateChanged(evt);
                }
            });  private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
            System.out.println(jComboBox1.getSelectedItem().toString());
        }
      

  2.   

    import java.awt.BorderLayout;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;

    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;


    public class Test {

    static JLabel label = new JLabel(" ");

    public static void main(String[] args) {
    JFrame f = new JFrame("Test");
    String[] list = {"a", "b", "c", "d"};

    JComboBox box = new JComboBox(list);
    box.addItemListener(new ItemListener() {

    @Override
    public void itemStateChanged(ItemEvent ie) {
    if(ie.getStateChange() == 1) {
    label.setText(ie.getItem().toString());
    }
    }

    });

    f.add(label);
    f.add(box, BorderLayout.SOUTH);
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    }

    }