Search code examples
javaswingjlayeredpane

Is this the proper way to overlay multiple components in one panel?


I'm trying to overlay a custom transparency over the top of a JPanel. I want both components to extend to the edge of the layered pane. I have overridden the paintComponent method of the top component to generally do nothing except when I want to display an overlay. Then it draws the appropriate text in the appropriate location.

Here is my solution for the layout problem:

JLayeredPane jlp = new JLayeredPane();
jlp.setLayout(new OverlayLayout(jlp) {
    @Override
    public void layoutContainer(Container target) {
        for (Component c: target.getComponents())
            c.setBounds(0, 0, target.getWidth(), target.getHeight());
    }
});

The question is - is there a better way to do this without overriding layoutContainer? This seems like a hack to me. I mean, really I can't believe that there isn't an option to do this when laying out components. But if I don't override the method, it leaves gaps on the top and left sides.

Am I missing something here, or is this the proper way to handle these requirements?


Solution

  • OverlayLayout wasn't designed to size all components to fill the entire space available. In effect you have created a customized layout manager. There is nothing wrong with this approach.

    I'm not sure why you are using a JLayeredPane. You should be able to just use a regular JPanel with the OverlayLayout and the multiple components.

    Or, if you want to use a JLayeredPane, then you probably don't need the OverlayLayout. You could add a ComponentListener to the layered pane and resize all components when a resized event is generated.