与JMenu不同,并不存在insertSeparator()方法。但是我们可以使用由Container继承的add(Component component, int position)方法。如果我们希望移除组件,可以使用JPopupMenu特定的remove(Component component)方法。
显示JPopupMenu
与JMenu不同,简单的组装弹出菜单并不够。我们需要将弹出菜单与合适的组件相关联。在Swing 5.0版本之前,我们需要添加事件处理代码来触发弹出菜单的显示。现在,我们所需要做的就是为我们希望关联弹出菜单的组件调用setComponentPopupMenu()方法。当平台特定的触发事件发生时,弹出菜单会自动显示。
我们只需要简单的创建JPopupMenu的实例,并将其关联到我们希望显示弹出菜单的组件,如下所示:
JPopupMenu popupMenu = ...;
aComponent.setComponentPopupMenu(popupMenu);
对于弹出菜单比较重要的JComponent方法主要有getComponentPopupMenu(), setComponentPopupMenu(), getInheritsPopupMenu(), setInheritsPopupMenu()以及getPopupLocation()方法。setInheritsPopupMenu()方法会接受一个boolean参数。当为true时,并没有直接为组件设置组件弹出菜单,则会查找父容器用于弹出菜单。
JPopupMenu属性
表6-9列出了JPopupMenu的16个属性。更多的属性是由JComponent,Container与Component继承的。
JPopupMenu属性
属性名
数据类型
访问性
accessibleContext
AccessibleContext
只读
borderPainted
boolean
读写
component
Component
只读
invoker
Component
只读
label
String
读写绑定
lightWeightPopupEnabled
boolean
读写
margin
Insets
只读
menuKeyListeners
MenuKeyListener[]
只读
popupMenuListeners
PopupMenuListener[]
只读
popupSize
Dimension
只写
selected
Component
只写
selectionModel
SingleSelectionModel
只写
subElements
MenuElement[]
只读
UI
PopupMenuUI
读写绑定
UIClassID
String
只读
visible
boolean
读写
JPopupMenu最有趣的属性就是lightWeightPopupEnabled。通常来说,JPopupMenu会尝试避免为显示其菜单项而创建新的重量级组件。相反,当JPopupMenu可以完整的显示在最外层的窗体框架内时弹出菜单使用JPanel。否则,如果菜单项不适合时,JPopupMenu使用JWindow。然而,如果我们在不同的窗体层上混合使用轻量级与重量级组件,在一个JPanel内显示弹出菜单并不会起作用,因为在菜单层显示的一个重量级组件会在JPanel之前出现。要纠正这种行为,弹出菜单使用Panel用来显示菜单选项。默认情况下,JPopupMenu绝不使用Panel。
如果我们需要允许Panel显示,我们可以在单个的JPopupMenu级别或是整个的Applet或是程序进行配置。在单独的弹出级别,只需要将lightWeightPopupEnable属性设置为false。在系统级别,可以通过如下的代码进行设置:
// From now on, all JPopupMenus will be heavy