Java Swing - JPanel vs JComponent

I play with Java Swing, and I'm really confused when it comes to JPanel vs. JComponent. According to CoreJava Vol 1 (cay horstmann):

Instead of extending the JComponent, some programmers prefer to extend the JPanel Class. JPanel is designed for a container that may contain other components, but you can also draw on it. There is just one difference. The panel is opaque, which means that it is responsible for painting all the pixels within its borders. The easiest way to achieve this is to paint the panel with the background color by calling the super.paintComponent method in the paintComponent method for each panel subclass:

class NotHelloWorldPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); . . . // code for drawing will go here } } 

I know what is opaque. What did he mean by "panel opaque .. responsible for painting all the pixels within its border"? If I read this correctly, he says that the panel will draw its own areas within its borders. Does JComponent do this too?

In the bottom line, I do not see the difference between JPanel and JComponent. Are there simple examples where I can REALLY see this?

Any help is appreciated

+6
source share
1 answer

JComponent is not required to draw all the pixels associated with it. It can remain transparent so you can see the components behind it.

To draw all the pixels, a JPanel is required.

Of course, if you do not call the super.paintComponent(..) method in any case, they will be more or less equivalent, since then you discard the guarantee that JPanel will draw the entire panel.

In short, the difference lies in already existing methods (namely the paint component).

EDIT:

An example of a ball class implemented using JComponent would look something like this:

(This will not work with JPanel since JPanel is opaque and the ball will have a square background. You could not call super.paintComponent , but as a rule, you should always or you break what the component really is. If I pass JPanel into something, they expect it to be a JPanel, not a JPanel hacked to behave like a JComponent)

 public class Ball extends JComponent { public Ball(int x, int y, int diameter) { super(); this.setLocation(x, y); this.setSize(diameter, diameter); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.fillOval(0, 0, width, height); } } 
+5
source

Source: https://habr.com/ru/post/955046/


All Articles