O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Add Translucence to Menus #12
Chapter 1, Basic JComponents
|
53
HACK
because the JMenu doesn’t draw what we think of as a menu—a list of menu
items that pop up when you click on the menu’s title. The
JMenu actually
only draws the title at the top of a menu. The rest of the menu is drawn by a
JPopupMenu
created as a member of the
JMenu
. Unfortunately this member is
marked
private
, which means you can’t substitute your own
JPopupMenu
subclass for the standard version.
Fortunately there is a way out. Like all Swing components, the menu com-
ponents delegate their actual drawing to a separate set of Look and Feel
classes in the
javax.swing.plaf
package. If you override the right
plaf
classes for the menu items and pop-up menu, then you should be able to
create the desired translucent effect. It just takes a little subclassing.
Make the Custom Menu Item
All MenuItems are implemented by some form of the javax.swing.plaf.
MenuItemUI
class. When creating custom UI classes, it is always best to start
by subclassing something in the
javax.swing.plaf.basic package (in this
case,
BasicMenuItemUI) because it handles most of the heavy lifting for you,
as shown in Example 1-28.
Example 1-28. Extending the basic UI
public class CustomMenuItemUI extends BasicMenuItemUI {
public static ComponentUI createUI(JComponent c) {
return new CustomMenuItemUI( );
}
public void paint(Graphics g, JComponent comp) {
// paint to the buffered image
BufferedImage bufimg = new BufferedImage(
comp.getWidth( ),
comp.getHeight( ),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bufimg.createGraphics( );
// restore the foreground color in case the superclass needs it
g2.setColor(g.getColor( ));
super.paint(g2,comp);
// do an alpha composite
Graphics2D gx = (Graphics2D) g;
gx.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER,0.8f));
gx.drawImage(bufimg,0,0,null);
}
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required