我正在为一个学校项目创建一台自动售货机,当用户点击A1、A2、B1、B2等时,我必须更新数字。小数点后的所有内容都会更改,但小数之前的所有内容都不会更改。因此,如果我单击A1,它设置为4美元50美分,然后我选择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));
}
});
}
});发布于 2021-04-07 02:26:25
你让这件事变得比原来更难了。首先,我将创建所有价值组合及其成本的映射,如下所示:
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.https://stackoverflow.com/questions/66974124
复制相似问题