所以我的任務(意外,作業!)是製作一個代表兩行數字時鐘的GUI。第一行是時鐘本身(hh:mm aa),第二行將日期顯示爲滾動文本(EEEE - MMMM dd,yyyy)。我已經設法讓所有這些顯示出來,但我無法弄清楚如何讓我的日期用我的電腦時鐘進行更新 - 這意味着我在1:47 PM運行它,並且它永遠不會變爲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();
}
}
}
}
任何有識之士將不勝感激!
讓我們來看看,如果我能得到這個展現出來吧... '公共無效重新計算(){ \t \t \t日期newDate =新的日期(); \t \t \t timeOutput = timeFormat.format(newDate); \t}' 嗯,我似乎無法讓它在這裏跳線,但這就是我最終做的(然後如你所說在TimeListener中調用它),它似乎工作。所以除非你覺得我錯過了一些我沒有注意到的重要東西,我認爲這樣做 - 謝謝你的幫助! – Jerm