I do have a screen in which i placed 3 panels like
- Main Panel
- Left panel
- Right Panel
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.
- How can i handle these case?
- Does somebody has a better solution?
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.