ActionPerformed on a JButton called more than once?

I am implementing a function that a function passes the selected item to a JList and value to a JTextField when users click on JButton.

I use several listeners. However, it seems that the actionPerformed loop inside addcartbtn is called twice when users click the button a second time and cause unwanted results. When users clicked a third time, the function is called three times.

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

Thank you all for your help!

+4
source share
2 answers

Do not add an ActionListener inside a ListSelectionListener - it makes no sense. You will add a lot of listeners without any goals. In fact, if you want the action to happen when the button is clicked, I see no reason at all for the ListSelectionListener. Just use the ActionListener that was added once in JButton, perhaps in the constructor or customization method.

In addition, a little less indentation can make your code more convenient for us. Edit: I have reduced the indentation of the code in the original post.

+3
source

You add a new action listener to your addcartbtn (would it not be more readable if it were called addCartButton, BTW) every time a choice was selected in JList. The listener should be added only once.

+3
source

Source: https://habr.com/ru/post/1412131/


All Articles