Java Reference
In-Depth Information
Rectangle leftRectangle = new Rectangle(
xLeft, yTop,
width / 3, width * 2 / 3);
Rectangle rightRectangle = new Rectangle(
xLeft + 2 * width / 3, yTop,
width / 3, width * 2 / 3);
Line2D.Double topLine = new Line2D.Double(
xLeft + width / 3, yTop,
xLeft + width * 2 / 3, yTop);
Line2D.Double bottomLine = new Line2D.Double(
xLeft + width / 3, yTop + width * 2 / 3,
xLeft + width * 2 / 3, yTop + width * 2 /
3);
118
119
Now you need to fill the rectangles and draw the lines. For the flag of Italy, the left
rectangle is green and the right rectangle is red. Remember to switch colors before
the filling and drawing operations:
g2.setColor(Color.GREEN);
g2.fill(leftRectangle);
g2.setColor(Color.RED);
g2.fill(rightRectangle);
g2.setColor(Color.BLACK);
g2.draw(topLine);
g2.draw(bottomLine);
Step 4 Combine the drawing statements with the component Ȓplumbingȓ.
public class MyComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// Your drawing code goes here
. . .
}
}
In our example, you can simply add all shapes and drawing instructions inside the
paintComponent method:
public class ItalianFlagComponent extends
JComponent
{
Search WWH ::




Custom Search