简体   繁体   中英

Child component with overridden paintComponent method draws component over top of JPanel

I have a parent JPanel that is using the OverlayLayout layout manager and the JPanel contains a main panel and and over lay panel.

eg

setLayout(new OverlayLayout(this));
add(overlayPanel)
add(mainPanel);

this is working fine, but the main panel contains lots of components outside of my control and a great many have overridden paintComponent and when they repaint they end up drawn on top of the overlay panel.

If I then resize the whole window the 2 panels display correctly stacked. Is there a way I can prevent this or receive a notification that a child component has redrawn so I can then repaint the whole window?

I did try to use a JLayeredPane, but I struggled as the main window can be resized and as it does not use a LayoutManager I had to set the bounds and I struggled to get this to work.

Normally a panel contains components painted in 2 dimensions so you can just repaint a single component and it won't affect other components. Painting is optimized for this situation.

However, when using the OverlayLayout, components are painted in 3 dimensions so painting a single component can affect other components. So you need to remove the optimized painting that is done by default:

JPanel main = new JPanel()
{
    @Override
    public boolean isOptimizedDrawingEnabled()
    {
        return false;
    }
};

main.setlayout( new OverlayLayout(main) );
main.add( overlayPanel );
main.add( backgroundPanel );

Or in your case it looks like you are extending JPanel, so you just need to override the isOptimizedDrawingEnabled() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM