我正在使用 JCheckBox 查找客户想要购买的商品,如果选择了 JCheckBox(hat),则总计 += hatprice,但它不会更新总计。 我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NgaFillimi extends JFrame implements ActionListener{
private JCheckBox hat;
private JLabel thetotal;
private int total = 0;
public NgaFillimi() {
Container c = getContentPane();
c.setLayout(new FlowLayout());
hat = new JCheckBox("hat");
thetotal = new JLabel("The total is " + total);
hat.addActionListener(this);
c.add(thetotal);
c.add(hat);
}
@Override
public void actionPerformed(ActionEvent evt) {
if (hat.isSelected()) {
total += 50;
}
}
public static void main(String[] args) {
NgaFillimi gui = new NgaFillimi();
gui.setSize(300,200);
gui.setVisible(true);
gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
gui.setTitle("GUI");
}
}
最佳答案
你正遭受“魔法思维”的困扰。是的,total
变量正在
已更改,但 JLabel 的文本不会仅仅因为总体更改而自行神奇地更改。 您一旦总计更改,编码人员必须通过在您的actionPerformed方法中重新调用thetotal.setText(...)
来自行更改它。
为什么你的代码不起作用?因为 JLabel 只知道它的文本被设置为字符串一次,仅此而已。它显示的 String 对象永远不会改变(也不会改变,因为字符串是不可变的)。同样,JLabel 更改其显示的唯一方法是显式调用其 setText
方法。
此外,如果您修复了代码,以便每次选择 JCheckBox 时 JLabel 都会适当更新,那么它的表现不会很好,因为每次取消选择然后重新选择 JCheckBox 时,总再次增加,这似乎不对。最好在未选择 JCheckBox 时删除 50,然后在选择 JCheckBox 时添加 50。
<小时/>I'm trying to what you said now that I fixed it, but it's getting negative, since I have a bunch of other JCheckBoxes
然后不要添加/减去,而是考虑为您的 gui 提供一个方法,例如称为 sumAllCheckBoxes()
并让所有 JCheckBox 监听器调用此方法,无论它们是否已选中或未选中。该方法会将总计清零 - total = 0;
,然后遍历所有 JCheckBox,如果选中 JCheckBox,则会增加成本,例如:
public void sumAllCheckBoxes() {
total = 0;
if (someCheckBox.isSelected()) {
total += someValue;
}
if (someOtherCheckBox.isSelected()) {
total += someOtherValue;
}
// .... etc...
// then set the text for theTotal here
}
最后它设置了 JLabel。关键是要考虑清楚您希望代码在程序的每一步执行什么操作。
关于java - JCheckBox 在选择时不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529241/