2

弹出菜单

我需要删除背景并BorderJPopupMenu. JPopupMenu应该是完全透明的。覆盖paintComponent不会产生积极的结果。我也尝试在BasicMenuItemUI/PopupMenuUIMenuItemUI/中找到解决方案,BasicPopupMenuUI但是发现渲染背景和边框不在其中。

public class CustomMenuItemUI extends BasicMenuItemUI {
    protected MouseInputListener mouseInputListener;
    protected MenuDragMouseListener menuDragMouseListener;
    public static ComponentUI createUI(JComponent c) {
        return new CustomMenuItemUI();
    }

    private static float alpha = 0.0f;
    private static float selectionAlpha = 0.0f;

    public static float getAlpha() {
        return alpha;
    }

    public static void setAlpha(float _alpha) {
        alpha = _alpha;
    }

    @Override
    public void installUI(JComponent c) {
        super.installUI(c);
        menuItem.setOpaque(false);
    }

    @Override
    public void paint(Graphics g, JComponent comp) {
        Graphics2D gx = (Graphics2D) g.create();
        gx.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        super.paint(gx, comp);
        gx.dispose();
    }

    @Override
    protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) {
        ButtonModel model = menuItem.getModel();
        Color oldColor = Color.red;
        int menuWidth = menuItem.getWidth();
        int menuHeight = menuItem.getHeight();
        if (model.isArmed() || (menuItem instanceof JMenu && model.isSelected())) {
            Graphics2D g2 = (Graphics2D) g.create(); 
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, selectionAlpha));
            g2.setColor(Color.red);
            g2.fillRect(0, 0, menuWidth, menuHeight);
        } else {
            g.setColor(Color.red);
            g.fillRect(0, 0, menuWidth, menuHeight);
        }
        g.setColor(oldColor);
    }

    @Override
    protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) {
        ButtonModel model = menuItem.getModel();
        if (model.isArmed() || model.isSelected() || !model.isSelected()) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
            super.paintText(g2, menuItem, textRect, text);
            g2.dispose();
        } else {
            super.paintText(g, menuItem, textRect, text);
        }
    }
    public static void setSelectionAlpha(float alpha) {
        selectionAlpha  = alpha;
    }
}

    String poppUI = CustomPopupMenuUI.class.getName(); 
UIManager.put("PopupMenuUI", poppUI);
4

1 回答 1

6

您可以更改PopupMenuUI代理的属性,但不能保证您选择的外观会遵守这些更改。更改应该在程序的早期,在任何 GUI 组件被实例化之前。

UIManager.put("PopupMenu.background", new Color(0));
UIManager.put("PopupMenu.border", BorderFactory.createEmptyBorder());

附录:正如@MadProgrammer 评论的那样,平台的对等组件可能是不透明的并且超出您的控制范围。您的代码 ( MenuTest, CustomPopupMenuUI, CustomMenuItemUI) 的外观如下所示com.apple.laf.AquaLookAndFeel。如果没有更好的解决方案,您可能会考虑实现自己的半透明窗口,如下所示

图片

于 2012-09-19T17:28:42.977 回答