代码之家  ›  专栏  ›  技术社区  ›  KobraCode

选中时JCheckBox未更新

  •  0
  • KobraCode  · 技术社区  · 7 年前

    我使用JCheckBox来查找客户想要购买什么,如果选择了JCheckBox(hat),那么total+=hatprice,但它不会更新total。 我的代码:

    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");
        }
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Hovercraft Full Of Eels    7 年前

    你正在遭受“魔法思维”的折磨。是的 total 变量 存在 改变了,但JLabel的文本不会因为完全改变而自行神奇地改变。 编码人员必须通过重新调用来更改它 thetotal.setText(...) 在actionPerformed方法中,一旦总数发生更改。

    为什么您的代码不起作用?因为JLabel只知道它的文本被设置为一个字符串,就这样。它显示的字符串对象从不更改(因为字符串是不可变的,所以也不能更改)。同样,JLabel更改其显示的唯一方法是显式调用 setText 方法

    此外,如果您修复了代码,使JLabel在每次选择JCheckBox时都会相应地更新,那么它的行为将不会很好,因为每次取消选择JCheckBox然后重新选择时,总增量都会再次增加,这似乎不正确。最好在取消选中JCheckBox时删除50,然后在选中后再添加50。


    我正在尝试你所说的,现在我修正了它,但它变得消极了,因为我有一堆其他的jcheckbox

    然后不要加/减,而是考虑给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。关键是要仔细考虑在程序的每个步骤中希望代码做什么。

        2
  •  0
  •   ifly6    7 年前

    您尚未更新实际 JLabel . 相反,您更新了 total 变量要更新 标签类 ,您将需要这样的代码 thetotal.setText("The total is " + total) .