我用Java编写了一个时钟,
它会显示时钟包括秒,
这就是我设置Timer
Timer timer = new Timer(1000, new TimerListener());
class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
repaint()
可用于“时钟”面板。
程序会正常显示时钟,
唯一的问题是时钟上的时间比实时慢1或2秒。
然后我将响应时间更改为100,
Timer timer = new Timer(100, new TimerListener());
这次与实时相比没有延迟。
我只是不明白为什么。有人可以向我解释Timer
是如何运作的,谢谢。
PS。 这是我的时钟代码
public class Clock extends JPanel {
public double hour;
public double minute;
public double second;
public Clock() {
setFont(Common.SetFont.font);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
FontMetrics fm = g.getFontMetrics(Common.SetFont.font);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = (int)(Math.min(xCenter, yCenter) * 0.7);
int radius1 = (int)(radius * 0.8);
g.drawOval(xCenter - radius, yCenter - radius, 2 * radius, 2 * radius);
for (int i = 1; i <= 12; i++) {
g.drawString(i + "", (int)(xCenter + radius1 * Math.sin(i * Math.PI / 6)) - (int)(fm.stringWidth(i + "") / 2), (int)(yCenter - radius1 * Math.cos(i * Math.PI / 6)) + (int)(fm.getAscent() / 2));
}
Calendar calendar = new GregorianCalendar();
hour = calendar.get(calendar.HOUR);
minute = calendar.get(calendar.MINUTE);
second = calendar.get(calendar.SECOND);
// draw hour line
g.drawLine(xCenter, yCenter, xCenter + (int)(radius1 * 2 / 5 * Math.sin(2 * Math.PI * (hour + minute / 60) / 12)), yCenter - (int)(radius1 * 2 / 5 * Math.cos(2 * Math.PI * (hour + minute / 60) / 12)));
//draw minute line
g.drawLine(xCenter, yCenter, xCenter + (int)(radius1 * 3 / 5 * Math.sin(2 * Math.PI * (minute + second / 60) / 60)), yCenter - (int)(radius1 * 3 / 5 * Math.cos(2 * Math.PI * (minute + second / 60) / 60)));
//draw second line
g.drawLine(xCenter, yCenter, xCenter + (int)(radius1 * 5 / 6 * Math.sin(2 * Math.PI * (second) / 60)), yCenter - (int)(radius1 * 5 / 6 * Math.cos(2 * Math.PI * (second) / 60)));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(2000, 1000);
}
}
这是时钟显示的代码
public class jClockAnimation extends JFrame {
Common.Clock clock = new Common.Clock();
public jClockAnimation() {
Timer timer = new Timer(100, new TimerListener());
add(clock, BorderLayout.NORTH);
add(new MessagePanel(), BorderLayout.SOUTH);
timer.start();
}
public static void main(String[] args) {
new Common.SetFrame(new jClockAnimation(), "Clock");
}
class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
class MessagePanel extends JPanel {
public MessagePanel() {
setFont(Common.SetFont.font);
}
@Override
protected void paintComponent(Graphics g) {
String string = new String((int)clock.hour + ": " + (int)clock.minute + ": " + (int)clock.second);
FontMetrics fm = g.getFontMetrics();
g.drawString(string, getWidth() / 2 - fm.stringWidth(string) / 2, getHeight() / 2 + fm.getAscent() / 2);
}
@Override
public Dimension preferredSize() {
return new Dimension(400, 200);
}
}
}