Introduction to Glass Panes in Swing

In the Java Swing classes JFrame and JApplet, the glass pane provides a unique and powerful feature. The glass pane is a layer above all other controls within the JFrame and JApplet. It allows you to paint above all other controls.

In addition to drawing graphics over the contents of a JFrame or JApplet, the glass pane can also be used to handle mouse events. Be aware that adding a mouse listener to the glass pane will prevent any mouse events from being sent to the controls below it.

The first example will demonstrate drawing graphics over all controls in the JFrame.

//Create a panel to use as the glass pane
JPanel panel = new JPanel()
{
public void paintComponent(Graphics g)
{
g.setColor(Color.red);

//Draw an oval in the panel
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
};

//Turn off the opaque attribute of the panel
//This allows the controls to show through
panel.setOpaque(false);

//Set the glass pane in the JFrame
setGlassPane(panel);

//Display the panel
panel.setVisible(true);
The results of the glass pane:


By setting the opaque attribute on the JPanel to false, it turns of the background of the JPanel. When the panel is painted, only the graphics in the paintComponent will be drawn without the background.

By simply modifying the paintComponent you can create a completely different effect. In the next example, we set the alpha level for the color. This allows a color to be painted while allowing the controls below it to be shown.
//Create a panel to use as the glass pane
JPanel panel = new JPanel()
{
public void paintComponent(Graphics g)
{
//Set the color to with red with a 50% alpha
g.setColor(new Color(1, 0, 0, 0.5f));

//Fill a rectangle with the 50% red color
g.fillRect(10, 10, this.getWidth() - 20, this.getHeight() - 20);
}
};

The results of glass pane:


This tutorial only covers the basics of using the glass pane. There are a number of interesting possible uses of the glass pane. Below are some ideas of things to try with the glass pane:
  • Create a transition effects between screens.
  • Display a progress screen within the glass pane.
  • Display debug information within the glass pane.
Related Links
Swing Hacks -Chapter 6 has some cool examples for creating a progress indicator in the glass pane.


2 comments:

Rvscript said...

RThis was exactly what i needed to better understand glassPanes . Unfortunately the java online tutorial from sun assumes to much of the reader.

spam-dev said...

Good idea for panel.

Post a Comment