在这段代码中,我试图在按下按钮时进行文本更新,但它似乎没有更新,即使变量的值在按下按钮时发生了变化。这是代码:
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);
}
}
答案 0 :(得分:2)
修改实例变量后,需要通过调用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
。