Change color of a Rectangle in a Swing application

This code example shows how to draw a rectangle in different colors.
In this case we paint directly on a JFrame, but it could be done with other components as well, like such as a JPanel.
On the JFrame we have added three buttons, one for each color (green, blue and red).

Change color of a rectangle in Swing

The important part when we’re going to draw something is to override the JFrame’s paint-method. Whenever the JFrame is repainted (like when the window is minimized and then restored again) the paint method is called. To decide which color to use we declare an instance variable that we use from our button-click methods to set the current color. The field declaration looks like this:

Since we don’t want to draw the rectangle at startup, but only when a button is clicked, the color variable is not assigned when first declared.
To set the color with which to draw the rectangle we simply assign that variable in each buttons click-method, and then call repaint() on the JFrame:

Finally we need to override the paint-method of the JFrame to do the actual drawing of the rectangle:

The method first calls the parents paint-method to keep the behavior of the JFrame class. Then it checks if the color is null (which it is at startup), if it’s not the color is set and the rectangle is drawn by calling the method fillRect on the Graphics object. In this case a filled square is drawn since it is 100 pixels in width and 100 pixels in height. It is drawn beginning at x-pos = 50 and y-pos = 50.

Below is the code for the entire class, including the initialization of the different components etc.

Search for more Java info on this site here:
Custom Search

Please type any questions here.