use*_*483 2 java swing background border jpopupmenu
JPopupMenu http://s010.radikal.ru/i313/1209/25/2213e2145879.gif
我需要删除的背景和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;
}
}
Run Code Online (Sandbox Code Playgroud)
String poppUI = CustomPopupMenuUI.class.getName();
UIManager.put("PopupMenuUI", poppUI);
Run Code Online (Sandbox Code Playgroud)
您可以更改PopupMenuUI委托的属性,但不能保证您选择的外观和服务将遵循更改.在实例化任何GUI组件之前,更改应该在程序的早期.
UIManager.put("PopupMenu.background", new Color(0));
UIManager.put("PopupMenu.border", BorderFactory.createEmptyBorder());
Run Code Online (Sandbox Code Playgroud)
附录:正如@MadProgrammer评论的那样,平台的对等组件可能是不透明的,并且无法控制.您的代码(MenuTest,CustomPopupMenuUI,CustomMenuItemUI),低于上显示的外观com.apple.laf.AquaLookAndFeel.在缺乏一个更好的解决方案,你可能看如图所示实现自己的半透明窗口在这里.
