有关actionlistener的JComboBox问题

时间:2015-03-11 16:12:10

标签: java swing actionlistener jcombobox

对于下面的例子,我正在编写一个数据为1,3,5,7,9的JComboBox,并期望在按下OK后它将变为2,4,6,8,10。然而它只是不起作用.....任何建议将不胜感激,谢谢。

public class Test extends JFrame{

Test (){
    final ArrayList<Integer> value = new ArrayList<>();
    value.add(1);                                                           
    value.add(3);                                                          
    value.add(5);                   
    value.add(7);
    value.add(9);
    final JComboBox pulldown = new JComboBox(value.toArray());
    add(pulldown);

    JButton ok = new JButton("OK");
    add(ok);

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
         int data [] = {2,4,6,8,10};                                       
         value.clear();
         for (int i=0; i < data.length; i++)
         {
         value.add(data[i]);  
         System.out.println(data[i]);
         }
        }
    });


}

public static void main(String[] args) {
    JFrame frame = new Test();
    frame.setLayout(new FlowLayout());
    frame.setSize(320, 240);
    frame.setVisible(true);
    frame.setResizable(true);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

}

2 个答案:

答案 0 :(得分:2)

您正在使用ArrayList数据来设置JComboBox的模型(这里可能是一个DefaultComboBoxModel),但后来更改了ArrayList的数据不应该是&#39;并且一旦设置好,可能不会改变模型(尽管对于其他收集可能存在发生这种情况的风险)。

最好继续使用DefaultComboBoxModel开始。

DefaultComboBoxModel<Integer>  model = new DefaultComboBoxModel<>();
model.addElement(1);                                                           
model.addElement(3);                                                          
model.addElement(5);                   
model.addElement(7);
model.addElement(9);

final JComboBox pulldown = new JComboBox(model);

然后您可以稍后更改模型的数据,并确保更改将反映在JComboBox的数据显示中。

答案 1 :(得分:0)

要从JComboBox中移除所有旧值,您需要调用方法myComboBox.removeAllItems()并向其中添加新项,您需要调用myComboBox.addItem(myobject)。更改代码的这一部分,

ok.addActionListener(new ActionListener() {


            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                pulldown.removeAllItems();//removing all previous items
                int data[] = { 2, 4, 6, 8, 10 };
                value.clear();
                for (int i = 0; i < data.length; i++) {
                     pulldown.addItem(data[i]);//adding new items
                }
            }
        });