-1

我正在尝试在面板上绘制圆圈,但圆圈的颜色由某些参数决定。首先,圆圈应该被涂成白色,然后进入一个 for 循环检查哪个参数匹配并且应该用那种颜色涂上圆圈。圆圈的位置存储在一个数组中。我到目前为止所做的代码不起作用。我显然做错了什么,但我是 Java 和编码的新手,所以我非常卡住。如果有人能告诉我如何编辑/更改我的代码,我将不胜感激。ArrayList circlesT 是圆位置的数组列表, temp 是具有值的数组,我也有参数。

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, 1000);    
    }
4

1 回答 1

3

几点。

  • 您不应该在方法调用结束后继续持有该Graphics对象。paintComponent
  • 一般来说,您应该使用javax.swing.Timer而不是java.util.Timer.
  • 您在计时器任务/操作中实际应该做的是更新数据的状态并调用repaint.
  • 完成所有绘画的代码应该paintComponent在它返回之前被调用。
于 2013-03-04T19:46:09.877 回答