Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Here, you can use setPreferredSize to specify the dimensions you need. You can specify the width to whatever you want (200 looks good to me). You can allow the height to remain autosized based on the amount of menu items by getting the default preferred size:

JMenuItem item = new JMenuItem();
item.setPreferredSize(new Dimension(200, item.getPreferredSize().height));

If you want to set the size of your JMenuItem (width in my case). You can change the width with this solution :

 JMenuItem returnMenu = new JMenuItem(action) {
            @Override
            public Dimension getPreferredSize() {
                Dimension preferred = super.getPreferredSize();
                Dimension minimum = getMinimumSize();
                Dimension maximum = getMaximumSize();
                preferred.width = Math.min(Math.max(preferred.width, 200),
                        maximum.width);
                preferred.height = Math.min(Math.max(preferred.height, minimum.height),
                        maximum.height);
                return preferred;
            }
        };

I just reused this solution : JMenuItem setMinimumSize doesn't work

It works better as you an see. Selected solution before This solution after I grant you, this is similar to the selected answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top