我正在制作一个业余RPG,我在战斗动态方面遇到了问题。当我按下攻击按钮时,我希望程序遵循程序中的attack()
方法。在actionPerformed()
方法中,它应该更新JLabel
。按下按钮时如何更新Jlabel
?
编辑:我忘记添加button.addActionListener(this);
现在可以了!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Battle extends JPanel implements ActionListener{
private JPanel panel;
private JLabel label1, label2;
private JButton button;
private int playerHealth = 100;
private int opponentHealth = 50;
private int playerDamage, opponentDamage;
public Battle(){
setPreferredSize(new Dimension(500,500));
setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new FlowLayout());
label1 = new JLabel("You : " + Integer.toString(playerHealth));
label2 = new JLabel("Opponent : " + Integer.toString(opponentHealth));
button = new JButton("Attack!");
panel.add(button);
add(label1, BorderLayout.WEST);
add(label2, BorderLayout.EAST);
add(panel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e){
attack();
label1.setText("You : " + Integer.toString(playerHealth));
label2.setText("Opponent : " + Integer.toString(opponentHealth));
}
public void attack(){
Random random = new Random();
playerDamage = random.nextInt(10) + 5;
opponentDamage = random.nextInt(5) + 5;
playerHealth = playerHealth - opponentDamage;
opponentHealth = opponentHealth - playerDamage;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Battle!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Battle());
frame.pack();
frame.setVisible(true);
}
}