How can i make a JPopupMenu transparent?

后端 未结 4 1397
暖寄归人
暖寄归人 2021-01-18 20:19

I\'d like to customize the look of JPopupMenu so i made a custom class extending the JPopupMenu class on i overrode the paintComponent method as i

4条回答
  •  孤街浪徒
    2021-01-18 20:56

    You don't have to extend JPopupMenu class, just make your menu non-opaque and then make the JMenuItems transparent instead (and non-opaque).

    public class CustomMenuItem extends JMenuItem {
            public void paint(Graphics g) { 
                    Graphics2D g2d = (Graphics2D) g.create(); 
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f)); 
                    super.paint(g2d); 
                    g2d.dispose(); 
            } 
    }
    

    enter image description here

    OR, do the opposite, extend JPopupMenu to make it transparent and keep both the menu and items non-opaque (this way there will be no opaque border of the menu like above).

    EDIT:

    Note that (unfortunately) it does not work when the popup menu exceeds the frame bounds, as @Durandal remarked.

    Though you could try to make some calculations and change location of popup (when needed) to keep it always inside the frame.

提交回复
热议问题