• Post Reply Bookmark Topic Watch Topic
  • New Topic

Code explination

 
David James Thompson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks for any help I may get.
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
David James Thompson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahh, thanks very much for that. That makes more sense now
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!