用Java动态更改区域的颜色

时间:2016-02-16 20:21:00

标签: java graphics

早上好, 我需要动态地改变几个区域的颜色。基本上我创建了一个类 Ovals ,在那个类中我创建了一个区域。在 View 类中,我创建了椭圆 ArrayList ,我在列表中添加了几个区域,并将它们绘制在不同的位置。 这是我的意思的源代码:

public class Objects{
    Area shape;
    public Objects(int x,int y){
        this.shape= new Area (new Ellipse2D.Float(x, y, 70, 70));
    }

    public Color randColor(){
        Color[]color = {
                Color.red,
                Color.BLUE,
                Color.cyan,
                Color.green,
                Color.pink,
                Color.black,
                Color.LIGHT_GRAY,
                Color.magenta,Color.orange,
                Color.white,Color.yellow,
                Color.darkGray
        };
     return color[randomPosition(color.length)];
    }

}

public class View extends JComponent{
        ArrayList<Objects> ob= new ArrayList<Object>();
        //stuff...

        public View()
        {
            addObjects();  
            //other stuff...
        }

        public void paintComponent(Graphics2D g2)
        {
            //if I set the color here with  the classical g2.setColor(Color.red) every object will be red
            drawOvals(g2);
        }


        public void addObjects(){
           for(int i=2;i<10;i++)
                ob.add(new Objects(i+10,100));
        }


        public void drawOvals(Graphics2D g2)
        {
            if(ob!=null){
                for(Objects o:op)
                {
                    //I waant to know for example if there is a way to set the color indipendently for each object
                    //I tried to put here: *g2.setColor(o.randColor())* but the paintComponent method is called every 10ms so the color changes very rapidly
                    g2.draw(o.shape);
                    g2.fill(o.shape);            
                }
            }
        } 
}

我知道这个问题有点长,但如果你知道如何解决这个问题请回答!非常感谢你!

1 个答案:

答案 0 :(得分:2)

您可以将颜色与每个椭圆相关联:

public class Objects{
    Area shape;
    Color color;

    public Objects(int x,int y){
        this.shape= new Area (new Ellipse2D.Float(x, y, 70, 70));
        color = randColor();
    }
...
}

然后在画椭圆之前:

 for(Objects o:op)
 {
     g2.setColor(o.color);
     g2.draw(o.shape);
     g2.fill(o.shape);            
 }