我正在实现一个函数,当用户单击 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!");
}
}
});
}
}
});
感谢大家的帮助!