基本上,我使用 Action 监听器来简单地将数字每秒加一。我正在使用计时器和 jlabel 来实现此目的。目前数字上升..1...2....3 等等,但是它会重新绘制自身,因此数字 2 将显示在 1 之上。我尝试将绘制方法移到 Action 监听器类中,但没有成功。有人愿意看看我哪里出错了吗?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class six1
{
public static void main (String Args[])
{
frame adam = new frame();
}
}
class frame extends JFrame
{
int counter = 0;
frame()
{
setSize(1000,1000);
setTitle("Adam,");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AL a = new AL();
Timer t1 = new Timer(1000, a);
t1.start();
setVisible(true);
}
public void paint (Graphics g)
{
g.setColor(Color.red);
g.drawString("" + counter, 500, 500);
}
class AL implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
counter++;
repaint();
}
}
}
谢谢
最佳答案
I'm using a timer and the jlabel for this to work.
您没有使用 JLabel,而是进行自定义绘制。
问题是你为什么要做定制绘画?更好的解决方案是使用 JLabel,然后仅使用 setText(...)
方法并让标签管理绘画。
此外,如果您确实使用自定义绘画,那么您应该重写 paintComponent()
方法,而不是 Paint() 方法。
关于java计数器重新绘制前一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20733608/