Search code examples
javaswingcolorsrectanglesrepaint

How can I recolor a rectangle?


So basically I have a class of a rectangle and I want to implement a method that changes its color after it has already been drawn.

Here´s my code so far. Thought it might work like changing the position of an object, but it didn´t.

public class rectangle extends JPanel(){

@Override
protected void paintComponent(Graphics g){
   super.paintComponent(g);
   g.setColor(Color.red)
   g.fillRect(0, 0, 30, 30);
}

public void recolor(){
  Color.blue;
  repaint();
}
}

Solution

  • Don't keep hardcoding values. When you use Swing components they have methods that allow you to dynamically change a property.

    For example all components have methods like:

    1. setFont(...)
    2. setBorder(...);
    3. setBackground(...);
    4. setForeground(...);

    In your case you don't even need a custom method. In your application code you can just use:

    someComponent.setForeground( Color.BLUE );
    

    Then in your painting code you use:

    @Override
    protected void paintComponent(Graphics g)
    {
       super.paintComponent(g);
       //g.setColor(Color.red)
       g.setColor( getForeground() ); 
       g.fillRect(0, 0, 30, 30);
    }
    

    If you don't want to use the foreground color property then you can add a custom property to your code. The basic steps would be

    1. create a method like setColor(Color color)
    2. create an instance variable "color" to save the property in your class
    3. customize the painting code to use the "color" property

    The above 3 steps would apply for any custom property to want to add to your class.