对JButton的ActionPerformed多次调用?

时间:2012-05-12 10:08:33

标签: java swing actionlistener

我正在实现一个函数,当用户单击JButton时,该函数传递JList中的选定项和JTextField中的值。

我正在使用几个听众。但是,当用户第二次按下按钮并产生不需要的结果时,似乎调用了addcartbtn内部的循环actionPerformed两次。当用户第三次按下时,该函数似乎被调用了三次。

   list.addListSelectionListener(new ListSelectionListener() {

        Map<String, Integer> cartlist = new HashMap<String, Integer>();

        public void valueChanged(final ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                System.out.println("test0");
                final ArrayList<String> cartArrayList = new ArrayList<String>();
                addcartbtn.addActionListener(new ActionListener() {

                    public void actionPerformed(final ActionEvent e2) {

                        System.out.println("test2");
                        String itemselected = "";
                        System.out.println("Index is " + e.getLastIndex());
                        String itemname = (String) hashmap.get(e.getLastIndex());
                        itemselected = itemname;

                        //System.out.println(itemselected);
                        try {
                            int insertedquantity = Integer.parseInt(quantity.getText());
                            cartlist.put(itemselected, insertedquantity);
                            //shoppingcart.revalidate();
                            String element = itemselected + " " + String.valueOf(insertedquantity);

                            cartArrayList.add(element);

                            System.out.println(element);
                            //System.out.println(counter);
                            shoppingcart.setListData(cartArrayList.toArray());
                            shoppingcart.revalidate();
                            shoppingcart.repaint();
                            System.out.println("---------");

                        } catch (NumberFormatException ex) {
                            System.out.println("Not a number!");
                        }
                    }
                });
            }
        }
    });

感谢大家的帮助!

2 个答案:

答案 0 :(得分:3)

不要在ListSelectionListener中添加ActionListener - 没有意义。你将无意添加许多听众。实际上,如果您希望仅在按下按钮时执行操作,我看不出任何ListSelectionListener的原因。只需使用已经一次添加到JButton的ActionListener,可能是在构造函数或设置方法中。

此外,减少一点缩进可能会使您的代码更容易被我们阅读 编辑:我减少了原始帖子中的代码缩进。

答案 1 :(得分:3)

每次在JList中进行选择时,您都会向addcartbtn添加一个新的动作侦听器(如果它被命名为addCartButton,BTW则不会更具可读性)。只应添加一次监听器。

相关问题