Chapter 1. Basic JComponents
Hack 11. Create Menus with Drop Shadows
Most custom effects require either subclassing a component or messing with graphics overlays. I tried a variety of techniques to create this hack, but I kept coming across the same problem over and over. If I wanted to draw a shadow, I had to change the sizing of each menu item, plus its background, plus the pop-up frame itself. That is a lot of components to manage. It would be a lot simpler if I could tell the components to make themselves a little bit bigger and give me the extra slice of screen real estate to draw in. The solution was right under my nose: the border. Every Swing component can use a custom border, without subclassing, and the border will automatically resize the component to fit. If the border is lopsided, then it will create a kind of shadow effect. Perfect!
Every standard Swing component is actually drawn by a UI helper class, and pop-up menus are no exception. I took the BasicPopupMenuUI in the javax. swing.plaf.basic package and created a subclass called CustomPopupMenuUI (shown in Example 1-25). It only does two things special: adds a custom border to the pop up's parent panel and sets the panel to be transparent.
Note:
1.when or where we should add the custom border to the parent of the JPopupMenu?
In the getPopup() method of the subclass of BasicPopupMenuUI.
2.The comment of
public static ComponentUI createUI(JComponent c){
throw new Error("ComponentUI.createUI not implemented.");
}
in ComponentUI.java :
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.
(this method will be invoked by java reflect system)