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();
}
}
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:
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
The above 3 steps would apply for any custom property to want to add to your class.