How to set a size for JMenuItem?

核能气质少年 提交于 2019-12-06 01:59:42

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!