Im currently trying to teach myself a bit of Java and was looking at a tutorial with the following code:
package painting;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
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);
}
}
What this does is creates a frame and displays the text "this is my custom panel" but what I dont get is how is the text displayed. I know I create the panel MyPanel with one constructor and two methods, getPreferredSize() and paintComponent(). I understand paintComponent is responsible for printing the text "this is my custom Panel" on to the panel but when I am adding the panel the code simply calls the constructor f.add(new MyPanel());. This constructor only creates the border. Nowhere in the code am I calling the paintComponent method so how is the code here getting executed?
Sorry if this is a silly question but I just dont seem to get it.
Thanks for any help I may get.
Read more https://community.oracle.com/message/12335723?tstart=0#12335723