【发布时间】:2021-07-02 13:27:20
【问题描述】:
我正在为学校项目创建自动售货机,当用户单击 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));
}
});
}
});
【问题讨论】:
-
代码应该以文本的形式发布在论坛中,而不是图像。发布适当的minimal reproducible example 来演示问题。我猜你需要保留一个“总”变量。因此,当您单击 A1 时,您会将金额添加到总数中。当您单击 D4 时,您将金额添加到总数中。然后在这两种情况下,您都使用“total”变量的新值更新标签。
标签: java swing user-interface actionlistener jtextfield