Java Reference
In-Depth Information
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle leftRectangle
= new Rectangle(100, 100, 30, 60);
. . .
g2.setColor(Color.GREEN);
g2.fill(leftRectangle);
. . .
}
}
That approach is acceptable for simple drawings, but it is not very object-oriented.
After all, a flag is an object. It is better to make a separate class for the flag. Then
you can draw different flags at different positions and sizes. Specify the sizes in a
constructor and supply a draw method:
public class ItalianFlag
{
public ItalianFlag(double x, double y, double
aWidth)
{
xLeft = x;
yTop = y;
width = aWidth;
}
public void draw(Graphics2D g2)
{
Rectangle leftRectangle = new Rectangle(
xLeft, yTop,
width / 3, width * 2 / 3);
. . .
g2.setColor(Color.GREEN);
g2.fill(leftRectangle);
. . .
}
private int xLeft;
private int yTop;
private double width;
}
119
120
You still need a separate class for the component, but it is very simple:
Search WWH ::




Custom Search