gpt4 book ai didi

java - Java Applet 中的文本更新

转载 作者:行者123 更新时间:2023-11-30 03:04:40 25 4
gpt4 key购买 nike

在这段代码中,我试图在按下按钮时更新文本,但它似乎没有更新,即使变量的值在按下按钮时确实发生了变化。这是代码:

public class Test extends Applet implements ActionListener
{
Button Clicker;
int CurrentClicks = 0;

public void init()
{
this.setSize(600,400);

Button Clicker = new Button("Button 1");
add(Clicker);
Clicker.addActionListener(this);

}
public void paint (Graphics g)
{
g.drawString("Test",300,50);
g.drawString(String.valueOf(CurrentClicks), 300, 100);
}
public void actionPerformed(ActionEvent ae)
{
System.out.println("Button 1 was pressed");
CurrentClicks++;
System.out.println("Current Clicks: "+CurrentClicks);
}
}

最佳答案

您需要通过调用repaint()来刷新容器修改实例变量后。

@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Button 1 was pressed");
CurrentClicks++;
System.out.println("Current Clicks: " + CurrentClicks);
repaint();
}

另外,请熟悉 Java naming conventions 。例如,建议将实例变量 CurrentClicks 命名为 currentClicks

关于java - Java Applet 中的文本更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35091728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com