Disabled Glass Pane
Posted by Rob Camick on November 7, 2008
There may be times when you want to temporarily disable your frame. The easiest way to do this is to simply use setEnabled(false) on the frame. There are two things I don’t really like using this approach:
- there is no visual indication the frame is disabled
- the frame beeps at you when you click on it
Maybe you also require a different solution?
Looking into the architecture of the top level Swing containers we find a Glass Pane. The Glass Pane is like an invisible sheet of class that is painted over the Root Pane of a top level container. Basically, the Glass Pane covers the menu bar and the content pane of the frame. By providing our own custom implementation of a Glass Pane we can get around the problems listed above.
The DisabledGlassPane class will get you started with a simple example of how this might be done. First of all it creates its own listeners to intercept all the mouse and key events when the glass pane is visible. Then it paints its own background. The trick to painting its background is to use a Color object with transparency. This will give the glass pane its disabled look. There are only two methods to use in this class:
- activate – makes the glass pane visible. You can specify some text to be displayed in the middle of the pane
- deactivate – makes the glass pane invisible again.
It is likely that you will want to activate the glass pane from within the ActionListener of a button. Using code like the following your frame will look like the frame in the image below:
DisabledGlassPane glassPane = new DisabledGlassPane();
JRootPane rootPane = SwingUtilities.getRootPane(...);
rootPane.setGlassPane( glassPane );
Although you can’t tell from the above image, the cursor will be changed to the wait cursor. You can use the setBackground(…) method of the glass pane to change the disabled effect. Using the setForeground(…) method will change the text color of the label.