How to set a size for JMenuItem?

Zalberth picture Zalberth · Oct 25, 2013 · Viewed 12.3k times · Source

enter image description here

As you can see, it's ugly to have these kind of JMenuItems. The width of the menu items is quite small.

Here is the code:

JMenu menuOne=new JMenu("MenuOne");
    JMenu menuTwo=new JMenu("MenuTwo");
    JMenu menuThree=new JMenu("MenuThree");
    JMenu menuFour=new JMenu("MenuFour");
    JMenuBar mbar=new JMenuBar();
    //add the menu to menubar
    mbar.add(menuOne);
    JMenuItem OneItOne=new JMenuItem("1");

    JMenuItem OneItTwo=new JMenuItem("2");
    menuOne.add(OneItOne);
    menuOne.addSeparator();
    menuOne.add(OneItTwo);
    mbar.add(menuTwo);
    mbar.add(menuThree);
    mbar.add(menuFour);
    setJMenuBar(mbar);

Simply adding some blanks in the String is okay (e.g. "1     "), but is there any better way to set a preferred length of JMenuItem? I've tried OneItTwo.setSize(), but failed.

Answer

Boann picture Boann · Oct 25, 2013

setPreferredSize(new Dimension(...)); works on menu items. setMinimumSize does not work though; it does not seem to be honored by the menu layout manager, so if you want to set a minimum that may be overridden by having larger content, or you want to set a minimum or preferred width without changing the height, you must override getPreferredSize() in a subclass. E.g.,

menuOne.add(new JMenuItem("1") {
    @Override
    public Dimension getPreferredSize() {
        Dimension d = super.getPreferredSize();
        d.width = Math.max(d.width, 400); // set minimums
        d.height = Math.max(d.height, 300);
        return d;
    }
});