如何解决动作监听器中的动作监听器
我正在为学校项目创建自动售货机,当用户点击 A1、A2、B1、B2 等时,我必须更新数字。小数点后的所有内容都会更改,但之前的任何内容都不会。因此,如果我单击设置为 4 美元 50 美分的 A1,然后我选择了 1 美元 5 美分的 D4,我的 JTextField
显示为 4 美元 5 美分。
这是 GUI 上的按钮:
public void cost() {
C_button.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
button_1.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.5;
cost_total.setText(String.valueOf(total_order));
}
});
button_2.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.25;
cost_total.setText(String.valueOf(total_order));
}
});
button_3.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.10;
cost_total.setText(String.valueOf(total_order));
}
});
button_4.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.05;
cost_total.setText(String.valueOf(total_order));
}
});
}
});
D_button.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
button_1.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.5;
cost_total.setText(String.valueOf(total_order));
}
});
button_2.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.25;
cost_total.setText(String.valueOf(total_order));
}
});
button_3.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.10;
cost_total.setText(String.valueOf(total_order));
}
});
button_4.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.05;
cost_total.setText(String.valueOf(total_order));
}
});
}
});
解决方法
你让这种方式变得比它应该的更困难。首先,我会创建一个包含所有价值组合及其成本的地图,例如:
Map<String,Double> costMap = new HashMap<>();
costMap.put("A1",4.5);
costMap.put("A2",4.25);
然后我会在某处创建一个字符串来跟踪用户输入:
String register = "";
然后创建一个操作来处理为大部分键按下的基本键:
public class VendingAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent arg0) {
register += getValue(Action.NAME);
if (costMap.containsKey(register)) {
costLabel.setText(costMap.get(register).toString());
register = "";
} else if (register.length() == 2) {
//handle bad choice
register = "";
}
}
}
然后当你创建你的按钮时,它会是这样的:
JButton buttonA = new JButton(new VendingAction("A"));
JButton buttonB = new JButton(new VendingAction("B"));
//so on and so forth.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。