Skip to main content

Colouring a rectangle

2 replies [Last post]
Joined: 2010-03-13


This is my first post, I want to draw a rectangle with a blue colour, but the problem is that the method is not recognized (this thing drives me mad) can you please help me to set the colour.

[code]import java.awt.*;

public class MonRectangle extends Rectangle {
//Les coordonn

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2010-03-13

Thank you for your useful post.

Joined: 2010-03-19

The colour of the Rectangle is not stored in the object, you simply must specify it when it is drawn. The setBackground( is not recognized because neither the Rectangle or MonRectangle class have a method setBackground(Color c).

In order to draw the Rectangle blue, find the method that will be painting the Rectangle (e.g. paintComponent() in a JPanel class) and override it so that the Color is set to blue when the Rectangle is drawn.

public void paintComponent(Graphics ga) {
super.paintComponent(ga); //Carries out normal painting
Graphics2D g = (Graphics2D) ga;
MonRectangle mr = this.getRectangle();//You will need to fill this bit
g.setPaint(;//change paint colour to blue
g.fill(mr); //paint rectangle