Skip to main content

Colouring a rectangle

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

Hi

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.

import java.awt.*;  </p>
<p>public class MonRectangle extends Rectangle {<br />
     //Les coordonnées<br />
     int PosX, PosY ;<br />
     int width, height;<br />
     //Constructeur<br />
     public MonRectangle(int PosX, int PosY, int width, int height){<br />
         setSize(width,height);<br />
         setLocation(PosX,PosY);<br />
         setVisible(true); // cannot find symbol<br />
         setBackground(Color.blue); // cannot find symbol<br />
     }<br />
 } 

Thank you in advance.

Reply viewing options

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

Thank you for your useful post.

crucialricky
Offline
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(Color.blue) 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.

e.g
@Override
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(Color.blue);//change paint colour to blue
g.fill(mr); //paint rectangle
}