I'm playing around with Java Swing and i'm really confused when comes to JPanel vs JComponent. According to CoreJava Vol 1 (cay horstmann):
Instead of extending JComponent, some programmers prefer to extend the JPanel class. A JPanel is intended to be a container that can contain other components, but it is also possible to paint on it. There is just one difference. A panel is opaque, which means that it is responsible for painting all pixels within its bounds. The easiest way to achieve that is to paint the panel with the background color, by calling super.paintComponent in the paintComponent method of each panel subclass:
class NotHelloWorldPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
. . . // code for drawing will go here
}
}
I know what opaque is. What does he meant by 'A panel is opaque .. responsible for painting all pixels within its bound'? If I read it correctly it says a panel will paint its own areas within its boundaries .. Doesn't JComponent does that too?
Bottom line is I couldn't see the difference between JPanel and JComponent. Is there a simple examples where I can REALLY see it?
Any help is appreciated
JPanel
is not alwaysOpaque
as it is already mentioned in Java Tutorials cited here (Problem 3, point 1) JPanel is not opaque for GTK+ Laf) . So it's always best to set it explicitly :-) – Mokpo