我使用 TimerTask 在我的一个类的循环上添加了一个计时器,该类由绘画组件类调用。基本上在已经绘制的页面上有白色圆圈,然后有一个 for 循环,它从数组中读取一个值,并且根据值的范围,圆圈会改变颜色。每个圆圈应该代表数组中的下一个值。但它不工作。我是一个基本的程序员,真的不明白出了什么问题。如果有人能帮帮我,我将不胜感激。到目前为止,这是我的代码:
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);
}