• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Code explination

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ahh, thanks very much for that. That makes more sense now
 
Would you like to try a free sample? Today we are featuring tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic