Hi guys, im just new to both these forms and Java and I was wondering if someone could help me out. I am currently trying to teach myself a bit of Java and was looking at a tutorial with the following code:
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.
Hi, and welcome to JavaRanch!
The Swing framework takes care of all the painting for you. In your example at line 25 you do ot only invoke the constructor of MyPanel (a JPanel) to create a new instance, but you also add that instance as a child component to a JFrame. When at line 27 you invoke setVisible() the JFrame is painted, along with it's child component. That ultimately results in an invocation of MyPanel's paintComponent() implementation somewhere down the line.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
David James Thompson
posted 5 years ago
Ahh, thanks very much for that. That makes more sense now