我正在构建一个简单的小程序,在我的小程序中,我有一个带下拉列表的组合框。当一个选项被选中,并点击 "add "按钮时,选择的内容会被接收并传递给一个创建对象的方法。唯一的问题是,当我点击按钮时,它很好地添加了对象,但是当我尝试添加另一个选择时,它删除了前一个选择,并将新的选择设置为与新选择相同的属性。所以本质上它是在重新添加选择。
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addTooObj(comboBox.getSelectedItem().toString(), lblStatusLabel);
System.out.println(comboBox.getSelectedIndex());
}
});
private void addToobj(String num,JLabel j){
System.out.println(num);
Object objToBeAdded = null;
long objNumber = Long.parseLong(num);
int quan = 0;
if (objNumber == 12354589621l) {
objToBeAdded = new Item(objNumber, 2.00, quan);
} else if (objNumber == 21) {
objToBeAdded = new Item(objNumber, 1.50, quan);
} else if (objNumber == 12) {
objToBeAdded = new Item(objNumber, 5.20, quan);
} else {
System.out.println("error");
}
oldObj.add(objToBeAdded);
}
在你的 actionPerformed
方法,你可以得到动作命令,并查看它被解雇的动作,然后只有当动作是你想要的动作时才调用你的方法。
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
System.out.println("The action was: " + action);
if(action.equals("What ever action you want")){
addTooObj(comboBox.getSelectedItem().toString(), lblStatusLabel);
System.out.println(comboBox.getSelectedIndex());
}
}