时间不会在 Applet 中重绘 [英] Time doesn't repaint in Applet
问题描述
我有一个小问题,但我不知道如何解决.我创建了简单的 Applet,其中应该是简单的数字时钟.我正确创建了所有方法,但重绘方法不会重绘我的小程序.你能检查我的代码并说出错误的地方吗?谢谢.
I have a small problem but I don't know to fix it. I create simple Applet in which should be simple digital clock. I created all methods correctly but repaint methods doesn't repaint my applet. Can you check my code and say where is mistake. Thanks.
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
.了解如何使用 Swing Timer
这是一个例子.但是我不是在你正在做的像 JApplet
这样的顶级容器上绘画,而是在更推荐的 JPanel
上绘画
Here's an example. But rather than painting on top-level container like JApplet
which you are doing, I'm painting on JPanel
which is more recommended
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
.这就是为什么我首先用我的例子来回答.
You'll want to avoid Thread.sleep
though. You may notice this causes flickering. It's preferred to use javax.swing.Timer
. That's why I answered with my example first.
这篇关于时间不会在 Applet 中重绘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!