Markus Lausberg
Markus Lausberg

Reputation: 12257

Hide JPanel without breaking the layout

I do have a screen in which i placed 3 panels like

Booth panels will have half of the parent panel size. I want to hide the left panel, without breaking the layout. and without chaning the layout manager (this is somehow hardcoded in my requirement 'BorderLayout'). The right panel still should have half of the size of the main panel.

My solution: I override the paint methods and added a boolean 'propHideContents'.

@Override
public void paintComponents(Graphics g) {
    if (propHideContents && isVisible()) {
        paintBlankPanel(g);
        return;
    }
    super.paintComponents(g);
}

@Override
protected void paintChildren(Graphics g) {
    if (propHideContents && isVisible()) {
        paintBlankPanel(g);
        return;
    }
    super.paintChildren(g);
}

private void paintBlankPanel(Graphics g) {

    Graphics scratchGraphics = (g == null) ? null : g.create();
    try {
        scratchGraphics.setColor(this.getBackground());
        scratchGraphics.clipRect(0, 0, this.getWidth(), this.getHeight());
    } finally {
        scratchGraphics.dispose();
    }
}

The hide logic looks like

public void setPropHideContents(boolean propHideContents) {
    if (this.propHideContents != propHideContents) {
        this.propHideContents = propHideContents;
        setEnabled(!propHideContents);
        if (getParent() != null) {
            getParent().repaint();
        }
    }
}

Nearly everything is working, but i do have a refresh problem durign the following testcase

I added 2 buttons to the screen. one for changing the visibility state and another one for the hiden state.

Booth panels are hidden and not shown. If i now press the 'visibility' button, the buttonis drawn in the area of the hidden panel. if i change the size if the screen manually with the mouse cursor, the repaint event is refreshing the hidden panels, and the incorrectly drawn object is removed.

  1. How can i handle these case?
  2. Does somebody has a better solution?

Upvotes: 1

Views: 825

Answers (2)

StanislavL
StanislavL

Reputation: 57381

Instead of just left and right panel place there a containers with CardLayout. Each container should have left (or right) panel and placeholder (e.g. one more panel). When you want to hide left (or right) panel just swap Cards showing empty panel.

Upvotes: 3

Ingo Kegel
Ingo Kegel

Reputation: 47975

Your solution is not workable and cannot be fixed. Painting does not exclusively originate from the parent component, a child component can be painted on its own if necessary (which is what you experience).

If you cannot use a different layout manager due to external requirements, you have to remove the contents of the left panel in order to hide them. Just wrap the children in another panel so that panel can be easily stored when it's removed.

Upvotes: 2

Related Questions