我有一个小问题,但我不知道要解决它.我创建了简单的Applet,其中应该是简单的数字时钟.我正确地创建了所有方法,但重绘方法不会重新绘制我的applet.你能检查我的代码并说出错误的地方吗?谢谢.
public class DigitalClock extends JApplet implements Runnable {
private Thread timeThread;
Date date = new Date();
public void start() {
timeThread = new Thread(this, "Clock");
timeThread.start();
}
@Override
public void stop() {
if (timeThread == null) {
return;
}
timeThread = null;
}
@Override
public void run() {
while (timeThread != null) {
repaint();
try {
timeThread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
@Override
public void paint(Graphics g) {
date.setTime(System.currentTimeMillis());
g.drawString(date.toString(), 50, 95);
}
}
解决方法:
只需使用javax.swing.Timer. See how to use Swing Timer
这是一个例子.但是,不是像JApplet那样在*容器上绘画,而是在JPanel上绘画,这是更推荐的
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
public class TimerPanel extends JPanel {
private String dateString;
private final SimpleDateFormat format;
private final Font font;
private final Date date;
public TimerPanel() {
format = new SimpleDateFormat("hh:mm:ss a");
font = new Font("impact", Font.PLAIN, 30);
date = new Date();
date.setTime(System.currentTimeMillis());
dateString = format.format(date);
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
date.setTime(System.currentTimeMillis());
dateString = format.format(date);
repaint();
}
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
FontMetrics fm = g.getFontMetrics(font);
int width = fm.stringWidth(dateString);
int height = fm.getAscent();
int x = getWidth() / 2 - width / 2;
int y = getHeight() / 2 + height / 2;
g.drawString(dateString, x, y);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 100);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TimerPanel timer = new TimerPanel();
JOptionPane.showMessageDialog(
null, timer, "Digital Clock", JOptionPane.PLAIN_MESSAGE);
}
});
}
}
更直接地回答你的问题,你的代码在我测试时工作,你唯一忘记做的就是调用super.paint().这样做后按预期工作
@Override
public void paint(Graphics g) {
super.paint(g);
你会想要避免Thread.sleep.您可能会注意到这会导致闪烁.最好使用javax.swing.Timer.这就是为什么我先回答我的例子.