gpt4 book ai didi

java - JPopupMenu 去除背景和边框

转载 作者:行者123 更新时间:2023-11-30 05:51:39 27 4
gpt4 key购买 nike

JPopupMenu

我需要删除 JPopupMenu 中的背景和 BorderJPopupMenu 应该是完全透明的。覆盖 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);

最佳答案

您可以更改 PopupMenuUI 委托(delegate)的属性,但不能保证您选择的外观会遵循这些更改。更改应该在程序的早期进行,在任何 GUI 组件被实例化之前。

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

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

image

关于java - JPopupMenu 去除背景和边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499574/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com