java - 动作监听器中的动作监听器
问题描述
我正在为学校项目创建自动售货机,当用户单击 A1、A2、B1、B2 等时,我必须更新数字。小数点后的所有内容都会更改,但之前的所有内容都不会更改。因此,如果我单击设置为 4 美元 50 美分的 A1,然后选择 D4,即 1 美元 5 美分,我的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 = "";
然后创建一个 Action 来处理为大部分键按下的基本键:
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.
推荐阅读
- mysql - 失去对带有表连接的 INFORMATION_SCHEMA.COLUMNS 表的查询
- c - 不使用双指针交换字符串
- azure - 微软认知服务人脸 API
- javascript - 将无操作或空处理程序绑定到 Vue 事件处理程序?
- ios - 如何使用 AlertBox 和 CoreData 从两个 UITableViewCell 传递数据?
- sql - 使用 join 语句创建 case 表达式;甲骨文
- telegram - 如何删除电报组
- theory - 理解 Coq 中“有根据的”证明
- gradle-kotlin-dsl - 将 sourceDir 添加到 java sourceSet
- jenkins - 如何在 Jenkins 中使用量角器?