I'm going through the book called Big Java by Cay Horstmann and I have a question about a graphics example in Chapter 2. My question is how is the RectangleComponent object "component" drawn out onto the frame without the "paintComponent" method being called? I understand that "Rectangle component = new RectangleComponent();" creates the new component object...does the paintComponent method just get called automatically when the object is created? I run the program it displays the two rectangles on the frame. Here is the code...
RectangleComponent.java
RectangleViewer.java
RectangleComponent.java
Code:
01: import java.awt.Graphics;
02: import java.awt.Graphics2D;
03: import java.awt.Rectangle;
04: import javax.swing.JComponent;
05:
06: /**
07: A component that draws two rectangles.
08: */
09: public class RectangleComponent extends JComponent
10: {
11: public void paintComponent(Graphics g)
12: {
13: // Recover Graphics2D
14: Graphics2D g2 = (Graphics2D) g;
15:
16: // Construct a rectangle and draw it
17: Rectangle box = new Rectangle(5, 10, 20, 30);
18: g2.draw(box);
19:
20: // Move rectangle 15 units to the right and 25 units down
21: box.translate(15, 25);
22:
23: // Draw moved rectangle
24: g2.draw(box);
25: }
26: }
RectangleViewer.java
Code:
01: import javax.swing.JFrame;
02:
03: public class RectangleViewer
04: {
05: public static void main(String[] args)
06: {
07: JFrame frame = new JFrame();
08:
09: frame.setSize(300, 400);
10: frame.setTitle("Two rectangles");
11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12:
13: RectangleComponent component = new RectangleComponent();
14: frame.add(component);
15:
16: frame.setVisible(true);
17: }
18: }