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

时间:2015-05-31 10:10:13

标签: 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();       
    }

1 个答案:

答案 0 :(得分:2)

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

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