I was trying to make rectangles that have multiple colors with Java AWT, but whenever I use the setForeground(color)
method, it changes the color of all objects in the window. Is there a way to change the color without that happening?
The code that I wrote looked like this:
setBackground(Color.WHITE);
setForeground(Color.BLACK);
g.fillRect(20,20,10,30);
setForeground(Color.BLUE);
g.fillRect(40,40,20,30);
The variable g was the Graphics object and I was writing a method in a class that extended the Canvas class.
I've looked for the solution for a long time, but I didn't find it anywhere.
You change the Color of the Graphics object:
//setForeground(Color.BLACK);
g.setColor( Color.BLACK );
g.fillRect(20,20,10,30);
//setForeground(Color.BLUE);
g.setColor( Color.BLUE );
g.fillRect(40,40,20,30);
Also, you really should be using Swing (not AWT) which is more advanced than AWT. Read the Swing tutorial on Custom Painting for more information and examples.