我需要删除背景并Border
在JPopupMenu
. JPopupMenu
应该是完全透明的。覆盖paintComponent
不会产生积极的结果。我也尝试在BasicMenuItemUI
/PopupMenuUI
和MenuItemUI
/中找到解决方案,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);