您的代码中的几个问题:
>在Swing GUI中没有while(true)循环或Thread.sleep.请改用Swing Timer.
>覆盖JPanel的paintComponent,而不是其paint方法.
> paintComponent(Graphics g)中的第一个调用应该是super.paintComponent(g),因此你的JPanel可以保持住宅并摆脱旧的图形.
编辑:
>我的坏,你的while(true)和Thread.sleep(…)将起作用,因为它们在后台线程中,但是,……
> Thread.sleep是一个静态方法,应该在类,Thread和.上调用
>我仍然认为Swing Timer会更容易实现.
>更简单的是,甚至不使用paint或paintComponent方法,而是简单地为显示器设置JLabel的文本.
例如.,
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Board2 extends JPanel {
private static final int TIMER_DELAY = 1000;
private int counter = 0;
private JLabel timerLabel = new JLabel("000");
public Board2() {
add(timerLabel);
new Timer(TIMER_DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
timerLabel.setText(String.format("%03d", counter));
}
}).start();
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Board2");
frame.getContentPane().add(new Board2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}