我已經使用了一個TimerTask來添加一個定時器在我的一個類被paint組件類調用的循環上。基本上已經在頁面上繪製了白色圓圈,然後是一個for循環,它從數組中讀取一個值,根據值的範圍,圓圈將改變顏色。每個圓應表示數組中的下一個值。但它不起作用。我是一個基本的程序員,真的不明白髮生了什麼問題。如果有人能幫我一把,我會很感激。這裏是我到目前爲止的代碼:TImerTask on paintComponent
public DoThePaint() {
String fileName;
fileName = "/Users/Desktop/test2.txt";
read = new Reader(fileName);
read.displayArrayList();
panel = new JPanel();
newImage = new ImageIcon(this.getClass().getResource("resource/background2T.png")).getImage();
circlesT = new ArrayList<Shape>();
circlesT.add(new Ellipse2D.Float(197.0f, 352.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(247.0f, 307.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(152.0f, 303.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(172.0f, 372.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(223.0f, 378.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(273.0f, 285.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(130.0f, 281.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(148.0f, 393.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(246.0f, 403.0f, 10.0f, 10.0f));
circlesT.add(new Ellipse2D.Float(297.0f, 264.0f, 10.0f, 10.0f));
}
public void paintComponent(Graphics g) {
drawShapes(g, circlesT);
}
public void drawShapes(Graphics g, final ArrayList<Shape> circlesT) {
final Graphics2D ga = (Graphics2D) g;
ga.drawImage(newImage, 0, 0, null);
for (int i = 0; i < circlesT.size(); i++) {
ga.draw(circlesT.get(i));
ga.setPaint(Color.white);
ga.fill(circlesT.get(i));
}
Timer timer = new Timer();
TimerTask t;
t = new TimerTask() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (read.temp.get(i) < 31 && read.temp.get(i) > 30) {
ga.draw(circlesT.get(i));
ga.setPaint(Color.green);
ga.fill(circlesT.get(i));
} else if (read.temp.get(i) < 32 && read.temp.get(i) > 31) {
ga.draw(circlesT.get(i));
ga.setPaint(Color.red);
ga.fill(circlesT.get(i));
} else if (read.temp.get(i) < 33 && read.temp.get(i) > 32) {
ga.draw(circlesT.get(i));
ga.setPaint(Color.yellow);
ga.fill(circlesT.get(i));
}
}
}
};
repaint();
timer.schedule(t, 0, 5000);
}
對不起,但沒有人會爲你調試你的代碼。你知道如何調試嗎?我建議你嘗試一下,然後發佈更多信息,如果你仍然堅持。 – Mick 2013-02-26 12:33:33
它不是它不工作。塗漆的物品似乎閃爍,然後在一段時間後全部消失。所以什麼都不會畫......真的很困惑,因爲我在做什麼錯誤 – user1961019 2013-02-26 13:32:03
a)不要把任何邏輯放入繪畫方法b)永遠不要在繪畫循環中添加調用重繪 – kleopatra 2013-02-26 13:35:09