问题描述
我想在JPopupMenu
中使用JCheckBoxMenuItem
.它的工作原理,但问题是,当一个复选框项目已被选中或取消选中弹出菜单中消失.因此,如果要选中/取消选中多个项目,则需要反复启动弹出窗口,这很烦人.
I want to use JCheckBoxMenuItem
s in a JPopupMenu
. It works, but the problem is that the popup menu disappears when a checkbox item has been checked or unchecked. So if one wants to check/uncheck several items, the popup needs to be launched repeatedly, which is irritating.
奇怪的是,如果我在菜单中仅使用普通的JCheckBox
项(而不是JCheckBoxMenuItem
s),则其行为应为应有的状态:弹出窗口停留在该位置,并且可以选中/取消选中复选框.完成后,只需在其外部单击即可关闭弹出窗口.
Curiously, if I use just plain JCheckBox
items in the menu (instead of JCheckBoxMenuItem
s), the behavior is just as it should be: the popup stays there and the checkboxes can be checked/unchecked. Once done, the popup can be closed just by clicking outside it.
当项为JCheckBoxMenuItem
时,如何使弹出窗口具有类似的行为?由于它们的外观,我更喜欢使用JCheckBoxMenuItem
.
How do I make the popup to behave like that when the items there are JCheckBoxMenuItem
s? I would prefer using JCheckBoxMenuItem
s because of their looks.
推荐答案
好,从 http://forums.sun.com/thread.jspa?threadID=5432911 .基本上,创建一个自定义UI:
Well, found working answer from http://forums.sun.com/thread.jspa?threadID=5432911. Basically, create a custom UI:
public class StayOpenCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI {
@Override
protected void doClick(MenuSelectionManager msm) {
menuItem.doClick(0);
}
public static ComponentUI createUI(JComponent c) {
return new StayOpenCheckBoxMenuItemUI();
}
}
并在JCheckBoxMenuItem
中进行设置:
myJCheckBoxMenuItem.setUI(new StayOpenCheckBoxMenuItemUI());
不知道这是否是最优雅的解决方案,但是效果很好.
Don't know if this is the most elegant possible solution, but works perfectly.
这篇关于选中其中的复选框时,如何防止JPopUpMenu消失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!