我正在制作一个程序,每当你按下一个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();
}
答案 0 :(得分:2)
您必须明确更新JLabel的文本:
if(one.isSelected()) {
i = i-f ;
label.setText("Health: " + i);
}