我在Swing的文本菜单中使用大图标。如果为菜单项设置了图标,则这些图标会导致菜单行展开。如果没有图标的菜单项或尺寸较小的图标,则会导致后续标签的位置不均匀,菜单项之间的距离也不同。
我现在可以:
是否有其他方法可以为文本菜单中的无图标菜单项设置菜单项图标spacer的最小尺寸?
答案 0 :(得分:0)
最佳做法是为没有图标的菜单项添加空/透明图标。您可以使用此方法合并图标(以创建相同的宽度/高度):
private static Icon mergeIcons(Icon icon1, Icon icon2, int x, int y, Component c) {
int w = 0, h = 0;
if (icon1 != null) {
w = icon1.getIconWidth();
h = icon1.getIconHeight();
}
if (icon2 != null) {
w = icon2.getIconWidth() + x > w ? icon2.getIconWidth() + x : w;
h = icon2.getIconHeight() + y > h ? icon2.getIconHeight() + y : h;
}
if (w < 1) w = 16;
if (h < 1) h = 16;
java.awt.image.ColorModel model = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment ().
getDefaultScreenDevice ().getDefaultConfiguration ().
getColorModel (java.awt.Transparency.BITMASK);
java.awt.image.BufferedImage buffImage = new java.awt.image.BufferedImage (model,
model.createCompatibleWritableRaster (w, h), model.isAlphaPremultiplied (), null);
java.awt.Graphics g = buffImage.createGraphics ();
if (icon1 != null) {
icon1.paintIcon(c, g, 0, 0);
}
if (icon2 != null) {
icon2.paintIcon(c, g, x, y);
}
g.dispose();
return new ImageIcon(buffImage);
}