Java Reference
In-Depth Information
Pay close attention to the call to getWidth inside the paintComponent method
of CarComponent . The method call has no implicit parameter, which means that
the method is applied to the same object that executes the paintComponent
method. The component simply obtains its own width.
Run the program and resize the window. Note that the second car always ends up at
the bottom-right corner of the window. Whenever the window is resized, the
paintComponent method is called and the car position is recomputed, taking the
current component dimensions into account.
ch03/car/CarComponent.java
1 import java.awt.Graphics;
2 import java.awt.Graphics2D;
3 import javax.swing.JComponent;
4
5 /**
6 This component draws two car shapes.
7 */
8 public class CarComponent extends JComponent
9 {
10 public void paintComponent(Graphics g)
11 {
12 Graphics2D g2 = (Graphics2D) g;
13
14 Car car1 = new Car( 0 , 0 );
15
16 int x = getWidth() - 60 ;
17 int y = getHeight() - 30 ;
18
19 Car car2 = new Car(x, y);
20
21 car1.draw(g2);
22 car2.draw(g2);
23 }
24 }
114
115
ch03/car/Car.java
1 import java.awt.Graphics2D;
2 import java.awt.Rectangle;
3 import java.awt.geom.Ellipse2D;
Search WWH ::




Custom Search