所以我的任务(惊喜,作业!)是制作一个图形用户界面,它代表一个有两条线的数字时钟。第一行是时钟本身 (hh:mm aa),第二行给出日期作为滚动文本 (EEEE - MMMM dd, yyyy)。我设法让所有这些都显示出来,但我不知道如何让我的日期与我的计算机时钟更新 - 这意味着我在下午 1:47 运行它,它永远不会更改为 1:48下午。我一直在阅读,似乎我的问题的答案是使用线程并拥有它try{Thread.sleep(1000)}
或类似的东西,但经过几个小时的实验,我不知道如何应用它我所拥有的:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class InnerClasses extends JFrame {
public InnerClasses() {
this.setLayout(new GridLayout(2, 1));
add(new TimeMessagePanel());
add(new DateMessagePanel());
}
/** Main method */
public static void main(String[] args) {
Test frame = new Test();
frame.setTitle("Clock");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 100);
frame.setVisible(true);
}
static class TimeMessagePanel extends JPanel {
DateFormat timeFormat = new SimpleDateFormat("hh:mm aa");
Date time = new Date();
private String timeOutput = timeFormat.format(time);
private int xCoordinate = 105;
private int yCoordinate = 20;
private Timer timer = new Timer(1000, new TimerListener());
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(timeOutput, xCoordinate, yCoordinate);
}
class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
}
static class DateMessagePanel extends JPanel {
DateFormat dateFormat = new SimpleDateFormat("EEEE - MMMM dd, yyyy");
Date date = new Date();
private String dateOutput = dateFormat.format(date);
private int xCoordinate = 0;
private int yCoordinate = 20;
private Timer timer = new Timer(250, new TimerListener());
public DateMessagePanel() {
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (xCoordinate > getWidth() - 50) {
xCoordinate = -50;
}
xCoordinate += 5;
g.drawString(dateOutput, xCoordinate, yCoordinate);
}
class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
}
}
任何见解将不胜感激!