我想在满足条件时更改paintComponent()对象的颜色

时间:2014-11-28 13:43:42

标签: java arrays swing paintcomponent repaint

我似乎无法理解这一点,我知道repaint()涉及但不确定如何使用它。 这是我的代码

public CarPanel()
    {
        repaint();
        rects = new Rectangle[]
        {
            new Rectangle(25, 35, 30, 80, Color.GREEN,"8"),
            new Rectangle(65, 35, 30, 80, Color.GREEN,"7"),
            new Rectangle(105, 35, 30, 80, Color.GREEN,"6"),
            new Rectangle(145, 65, 30, 50, Color.GREEN,"2"),
            new Rectangle(185, 65, 30, 50, Color.green,"1"),
            new Rectangle(25, 170, 30, 50, Color.GREEN,"13"),
            new Rectangle(65, 170, 30, 50, Color.GREEN,"12"),
            new Rectangle(105, 170, 30, 50, Color.GREEN,"11"),
            new Rectangle(145, 170, 30, 50, Color.GREEN,"3"),
            new Rectangle(190, 160, 92, 80, Color.BLACK,"Attendant Station"),
            new Rectangle(25, 280, 30, 50, Color.GREEN,"15"),
            new Rectangle(65, 280, 30, 50, Color.GREEN,"14"),
            new Rectangle(105, 280, 30, 80, Color.GREEN,"10"),
            new Rectangle(145, 280, 30, 80, Color.GREEN,"9"),
            new Rectangle(185, 280, 30, 50, Color.GREEN,"5"),
            new Rectangle(225, 280, 30, 50, Color.GREEN,"4")     
        };
    }//end carPark

    public void changeShapeColor(){

    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        this.setBackground(Color.white);

        for (Rectangle rect : rects) {               
            g.setColor(Color.BLACK);
            g.drawString(rect.number, rect.x, rect.y);
            g.setColor(rect.color); 
            g.fillRect(rect.x, rect.y, rect.w, rect.h);
        }//end for
    }//end paintComponent
}//end JPanel

当代码中的其他地方满足条件时,我想将颜色从绿色更改为红色。 非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:1)

public void changeShapeColor(Color newColor) {
    for (Rectangle rect : rects) {
        rect.color = newColor;
    }
}

然后在条件发生变化时调用changeShapeColor - 方法。并确保您的组件无效,因此将重新绘制。

答案 1 :(得分:1)

一种方法是将Rectangle更改为采用颜色函数而不是颜色,因此请使用如下代码结构:

public class Rectangle {
   private ColorFunction function;
   // ... etc

   public Color getColor() { return function.getColor(); }
}

public interface ColorFunction {
   public Color getColor();
}

public class MyColorChoice implements ColorFunction {
   public Color getColor() {
      return isConditionMet() ? Color.RED : Color.GREEN;
   }
}