我試圖做一個數字時鐘,然後添加到JPanel
,現在,當我打電話DrawString
外taskPerformer
方法,它吸引,但裏面的時候,它不會繪製字符串!爲什麼會這樣,我該如何去實施這個課程,以便每一秒重繪?更新的DrawString在一定的時間間隔
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.Timer;
class DrawDate extends JPanel {
public Date ddate;
public Calendar ccalendar = new GregorianCalendar();
Date time;
public DrawDate() {
this.ddate = new Date();
time = this.ccalendar.getTime();
}
public void paint(Graphics g) {
final Graphics2D g2 = (Graphics2D)g;
Font font = new Font("Arial", Font.PLAIN, 50);
g2.setFont(font);
//THIS DRAWS THE STRING
g2.drawString(time.toString() , 100, 100);
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Calendar ccalendar = new GregorianCalendar();
Date time = ccalendar.getTime();
//THIS DOES NOT DRAW A STRING.
g2.drawString(time.toString() , 200, 100);
}
};
final Timer timer = new Timer(1000, taskPerformer);
timer.start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
super.setBackground(new Color(100,100,100));
paint(g);
}
}
http://www.oracle.com/technetwork/java/painting-140037.html?printOnly=1可能是值得一讀 – 2014-01-05 09:44:53