java - JButton 上的 ActionPerformed 调用不止一次?

标签 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!");
                        }
                    }
                });
            }
        }
    });

感谢大家的帮助!

最佳答案

不要在 ListSelectionListener 中添加 ActionListener —— 没有意义。您将无缘无故地添加许多听众。事实上,如果您希望仅在按下按钮时发生操作,我认为根本没有理由使用 ListSelectionListener。只需使用已添加一次到 JButton 的 ActionListener,可能是在构造函数或设置方法中。

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

关于java - JButton 上的 ActionPerformed 调用不止一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10562781/

相关文章:

java - 如何在 Swing GUI 中启动 JTable?

java swing 组合框

java - 从 Java 中的按钮运行可执行程序

java - 如何使用 javaFx TriangleMesh 创建这样的形状?

JavaFX:逐渐更改绑定(bind)到后台线程中的 DoubleProperty

java - 如何使用复选框列表在struts 2中获取多个复选框值

java - JFrame背景图像设置背景图像时,其他按钮不会出现在框架上?

java - 什么会导致这个特定的回文出现逻辑错误

java - 如何将一个 Action 监听器分配给几个按钮?

java - 无法从另一个函数向 Java 中的 JTextArea 添加文本