Skip to content
Advertisement

JComponent not being drawn on JLayeredPane, JPanel is

I’ve added a JLayeredPane to a JFrame. To said pane i’ve added a JComponent with overloaded paintComponent(Graphics g) method, which calls super.paintComponent(g) among other things. The JComponent also has setBackground(Color.RED) and setBounds(0, 0, 100, 100) in its constructor.

The problem is, the JComponent isn’t being drawn at all it seems. However, if i change the class being extended by the JComponent to JPanel, it works just fine.

Does it matter at all? I would like to know why it works this way, it seems like extending JPanel when i don’t care for its additions is just unnecessary overhead.

Thanks for your time.

Advertisement

Answer

The JComponent also has setBackground(Color.RED)

On its own that will do nothing.

A JComponent has no default painting code, so invoking super.paintComponent() will NOT cause any background to be painted.

If you want to paint the background you need to add your own custom painting code:

g.seColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement