How to set the minimum height and icon with of a text menu or context menu item?

158 Views Asked by At

I use big icons in text menus in Swing. Those icons cause a menu row to expand if an icon is set for the menu item. This leads to an inhomogeneous position of the following label and different distance between menu items if there are menu items without icons or with icons of a smaller size.

I may now:

  • resize the Icons
  • insert empty, transparent icons for menu items without icon
  • ?

Are there other ways to set the minimum size of the menu items icon spacer for icon-less menu items in text menus?

1

There are 1 best solutions below

1
On

Best practice is to add empty/transparent icons for menu items w/o icons. You can merge icons (to create sames width/height) with this method:

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);
}