如何通过按下 JButton 来更改整数的值?

How to change the value of an integer by pressing a 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);
}