代码在下面。基本上我想要做的是在我的 JTextPane 的 JPanel 中进行显示。我有一个按钮,用于编辑应该在 JTextPane 中显示的字符串的值。但是,我不知道如何更新 JTextPane。我已经尝试过 revalidate()、validate()、repaint(),这些似乎都不起作用。
代码完成了,应该可以运行了。
导入 java.awt.Canvas;
public class windowBuild extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int health = 20;
private int energy = 4;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
windowBuild frame = new windowBuild();
frame.setVisible(true);
}
});
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
if (which.equals("Claw")){
energy = energy-1;
System.out.println("Player one's dragon clawed the opponent. Dragon's energy is now at: "+ energy);}
else if (which.equals("Wait")){
System.out.println("Turn succesfully skipped");}
System.out.println(getEnergy());
}
}
public windowBuild() {
ButtonHandler bh;
System.out.println("Starting frame...");
bh = new ButtonHandler();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new TitledBorder(null, "Dragon Duel",
TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnClaw = new JButton("Claw");
btnClaw.setBounds(288, 511, 109, 39);
contentPane.add(btnClaw);
btnClaw.addActionListener(bh);
if (energy == 0)
btnClaw.setEnabled(false);
JButton btnWait = new JButton("Wait");
btnWait.setBounds(645, 511, 109, 39);
contentPane.add(btnWait);
btnWait.addActionListener(bh);
StringBuilder sb = new StringBuilder();
String strB = Integer.toString(health);
sb.append("H: ").append(strB).append("/20");
String healthString = sb.toString();
JTextPane txtpnH_1 = new JTextPane();
txtpnH_1.setEditable(false);
txtpnH_1.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH_1.setText(healthString);
txtpnH_1.setBounds(134, 511, 109, 39);
contentPane.add(txtpnH_1);
String strR = Integer.toString(energy);
String energyString = "E: ";
energyString += strR;
energyString += "/4";
JTextPane txtpnH = new JTextPane();
txtpnH.setEditable(false);
txtpnH.setText(energyString);
txtpnH.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH.setBounds(39, 511, 85, 39);
contentPane.add(txtpnH);
}
}
非常感谢!!