JMenuItem setMinimumSize 不起作用 [英] JMenuItem setMinimumSize doesn't work
问题描述
我尝试为菜单项设置最小宽度,但似乎不起作用.这是我的函数,它创建项目:
I try to set a minimum width for my menu items, but it doesn't seem to work. Here is my function, which creates the items:
private JMenuItem newItem(String text, String iconPath) {
JMenuItem myMenuItem;
if (iconPath == null || iconPath.isEmpty()) {
myMenuItem = new JMenuItem(text);
}
else {
ImageIcon icon = new ImageIcon(iconPath);
myMenuItem = new JMenuItem(text, icon);
}
// this would work, but then setMaximumSize doesn't have any effect
// myMenuItem.setPreferredSize(new Dimension(250,20));
myMenuItem.setMinimumSize(new Dimension(250,20));
myMenuItem.setMaximumSize(new Dimension(350,20));
return myMenuItem;
}
我做错了什么?
附注.我在 Windows XP、Servicepack 3 上使用 jdk1.6 和 System Look&Feel
PS. I'm using jdk1.6 on Windows XP, Servicepack 3 with the System Look&Feel
推荐答案
最小和最大尺寸被大多数布局管理器忽略.这是一个有用的小技巧,可以强制在任何布局管理器中遵守这些尺寸:
Minimum and maximum sizes are ignored by most layout managers. Here is a useful little trick that forces those sizes to be respected in any layout manager:
private class MyMenuItem extends JMenuItem {
@Override
public Dimension getPreferredSize() {
Dimension preferred = super.getPreferredSize();
Dimension minimum = getMinimumSize();
Dimension maximum = getMaximumSize();
preferred.width = Math.min(Math.max(preferred.width, minimum.width),
maximum.width);
preferred.height = Math.min(Math.max(preferred.height, minimum.height),
maximum.height);
return preferred;
}
}
即使菜单项的内容发生变化,这也有好处.您需要添加构造函数以满足您的目的.
This has the advantage of working even if the contents of the menu item changes. You will need to add constructors to suit your purposes.
这篇关于JMenuItem setMinimumSize 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!