Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

How does paintComponent() get called by JFrame?

$
0
0
I'm working through the Java "Performing custom painting" tutorial My link

I've noticed that two methods called paintComponent and getPreferredSize, the former of which accepts a Graphics object as a parameter, are used to help design the GUI.
However, they don't appear to be called or referenced anywhere in the code.

Could anybody explain to me where they are called from, or point me to the part in the Java API which explains it?

This is the code I am referring to:

public class SwingPaintDemo2 {
   
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI(); 
            }
        });
    }

    private static void createAndShowGUI() {
        System.out.println("Created GUI on EDT? "+
        SwingUtilities.isEventDispatchThread());
        JFrame f = new JFrame("Swing Paint Demo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MyPanel());
        f.pack();
        f.setVisible(true);
    }
}

class MyPanel extends JPanel {

    public MyPanel() {
        setBorder(BorderFactory.createLineBorder(Color.black));
    }

    public Dimension getPreferredSize() {
        return new Dimension(250,200);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);       

        // Draw Text
        g.drawString("This is my custom Panel!",10,20);
    }  
}


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>