This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JPanel question  RSS feed

 
Jacob Collins
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • 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?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • 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.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!