我在使用Java繪圖時遇到問題。我認爲我的代碼是正確的,但是當我把它放到循環計時器時,它不會打印任何東西。我想每秒重複doDrawing(g)方法。現在它只會打印文本prom system.out但不繪製。使用計時器繪圖不起作用
package src;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JPanel;
import javax.swing.Timer;
public class surface extends JPanel{
private void doDrawing(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
//souradnice stredu ciferniku
final int sx = 250;
final int sy = 250;
// inicializace promennych
int uhel = 0;
int delka = 150;
int xHodina,xMinuta,xSekunda,
yHodina,yMinuta,ySekunda;
// získání aktuálního času
int HOUR = Calendar.getInstance().get(Calendar.HOUR);
int MINUTE = Calendar.getInstance().get(Calendar.MINUTE) + 1;
int SECOND = Calendar.getInstance().get(Calendar.SECOND) + 1 ;
//výpočet jednotlivých úhlů pro jednotlivé ručičky a jejich vykreslení
xSekunda = (int) ((int) sx + Math.round(Math.sin((6 * SECOND * Math.PI/180)) * delka));
ySekunda = (int) ((int) sy - Math.round(Math.cos((6 * SECOND * Math.PI/180)) * delka));
//vyhreslení ručiček
g2d.drawLine(sx, sy, xSekunda, ySekunda);
//info
System.out.print(" "+(6 * SECOND)+ " "+ HOUR+" "+MINUTE+" "+SECOND+" "+xSekunda+" "+ySekunda+"\n");
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
int delay = 1000; //milliseconds
//Somewhere there is that problem ..
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
doDrawing(g);
}
};
new Timer(delay, taskPerformer).start();
}
}
問題出在這裏。
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
int delay = 1000; //milliseconds
//Somewhere there is that problem ..
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
doDrawing(g);
}
};
new Timer(delay, taskPerformer).start();
}
}
,切勿啓動的paintComponent內部的定時器。這種方法僅適用於繪圖和繪圖,沒有任何其他內容。 – 2015-02-17 21:46:40