user3001286
user3001286

Reputation:

Change the color dynamically of an Area in Java

Good morning, I need to change the color of few areas dynamically.Basically I created a class Ovals and in that class I created an area. In the View class I created an ArrayList of Ovals and I added few areas to the list and I drew them in different positions. Here is the source code of what I mean:

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);            
                }
            }
        } 
}

I know this question is a bit long, but if you know how to solve this please answer! thank you very much!!

Upvotes: 0

Views: 855

Answers (1)

djebeeb
djebeeb

Reputation: 191

You could have a Color associated with each oval:

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();
    }
...
}

Then right before you draw the oval:

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

Upvotes: 1

Related Questions