• 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

JPanel question

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
On p. 364 of Head First Java is the following code:

class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
// other code here
}
}

OK, but what the book doesn't make clear is:
1) WHY is it necessary to extend JPanel? Why not just use it directly?
2) Since we have to extend JPanel into its own class to use it, then why isn't JPanel an interface instead of a class?
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't have the book in front of me, but from what you've posted, it looks like JPanel is being extended for the purpose of overriding the paintComponent method. In other words, you're getting a JPanel, but with a "customized" paintComponent method. If you didn't want that customized behavior, you could simply create a new JPanel.
 
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Swing is built on concrete inheritance. If you want to implement custom painting for a JPanel the only easy way of going about it is to extend it and override paintComponent(). I suspect you may be having the same gag reflex I did when trying to work with Swing. It's a massive heirarchy of concrete inheritance more than half a dozen levels deep. Implementation is exposed all over the place. My life got a lot easier when I stopped trying to make Swing components elegant and simply went about isolating the ugly Swing code from the rest of the application.
 
You guys haven't done this much, have ya? I suggest you study this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic