Java graphics question

Discussion in 'Mac Programming' started by smb, Jan 4, 2010.

  1. smb macrumors newbie

    Joined:
    Jul 10, 2009
    #1
    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

    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: }
    
     
  2. Matthew Yohe macrumors 68020

    Joined:
    Oct 12, 2006
    #2
    paintComponent is called automatically anytime the RectangleComponent "component" needs to be displayed on the screen (ie nothing is actually drawn until you call frame.setVisible)

    You don't call paintComponent directly since it is event triggered (covering/uncovering the component with another window) but in some cases, you may need to have paintComponent called. Here you would use the repaint method from the Component class.
     
  3. smb thread starter macrumors newbie

    Joined:
    Jul 10, 2009
    #3
    That makes sense and the book actually said this (I must've skimmed over it too quick). Thanks for your help.
     

Share This Page