java - 如何通过按 JButton 来更改整数值?

标签 java swing jbutton

我正在编写一个程序,每次按下 JButton 时都会减少 int 的值。我想让每次按下按钮时 i 减少 20。 这是一个例子:

    static int i = 100;
    static final int f = 20;

    public static void main(String[] args) {
        JPanel content = new JPanel();          
        JButton one = new JButton("Move 1");
        JLabel label = new JLabel ("Health: " + i);         
        content.add(one);
        content.add(label);         
        one.addActionListener(new ActionListener(){ 
            public void actionPerformed(ActionEvent e) {    
                if(one.isSelected()) {                      
                    i = i-f ;
                }
            }
        });
        JFrame window = new JFrame("Fight!"); 
        window.setContentPane(content); 
        window.setSize(400,400); 
        window.setLocation(300,150); 
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.repaint();       
    }

最佳答案

您必须明确更新 JLabel 的文本:

if(one.isSelected()) {
   i = i-f ;
   label.setText("Health: " + i);
}

关于java - 如何通过按 JButton 来更改整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30556216/

相关文章:

java - 同一对象的迭代器不独立运行

java - 如何更新和打印我的 "estimatedCost"Double? Java新手

java - 是否有用于 Eclipse 3.4 的 jface 数据绑定(bind)框架的良好示例和文档?

java - 小程序在浏览器中显示为空

java - 单击按钮时关闭容器

java - getRootPane() 默认按钮 - 这是一个错误吗?

c# - 如何从 C# 执行 Java 程序?

java - JXTable 列排序在 1.0 和 1.6 之间发生变化

java - 当调用新的 JPanel 时,单击 JButton 时随机生成数字

java - 在 Action 事件期间在标签中设置文本