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);
}
}

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.