如果要继续使用(这很好,因为它以跨平台的方式处理弹出窗口的鼠标和键盘调用),则可以覆盖以选择适当的行。setComponentPopupMenu
JPopupMenu.show(Component, int, int)
JPopupMenu jPopupMenu = new JPopupMenu() {
@Override
public void show(Component invoker, int x, int y) {
int row = jList.locationToIndex(new Point(x, y));
if (row != -1) {
jList.setSelectedIndex(row);
}
super.show(invoker, x, y);
}
};
jList.setComponentPopupMenu(jPopupMenu);
请注意,当通过键盘调用弹出窗口时(并且您不会在目标组件上覆盖),您进入的x,y位置将是组件的中点。如果在这种情况下已有选择,您可能不想更改选择。getPopupLocation
JPopupMenu.show
我想出的解决键盘与鼠标调用问题的解决方案是在组件上设置一个客户端属性,并在覆盖中,然后在显示弹出窗口时对其进行检查。通过键盘调用时将出现的参数。下面是核心代码(可能在可用于组件及其弹出菜单的实用程序类中实现)。getPopupLocation
getPopupLocation
null
private static final String POPUP_TRIGGERED_BY_MOUSE_EVENT = "popupTriggeredByMouseEvent"; // NOI18N
public static Point getPopupLocation(JComponent invoker, MouseEvent event)
{
boolean popupTriggeredByMouseEvent = event != null;
invoker.putClientProperty(POPUP_TRIGGERED_BY_MOUSE_EVENT, Boolean.valueOf(popupTriggeredByMouseEvent));
if (popupTriggeredByMouseEvent)
{
return event.getPoint();
}
return invoker.getMousePosition();
}
public static boolean isPopupTriggeredByMouseEvent(JComponent invoker)
{
return Boolean.TRUE.equals(invoker.getClientProperty(POPUP_TRIGGERED_BY_MOUSE_EVENT));
}
然后在组件中重写:getPopupLocation
@Override
public Point getPopupLocation(MouseEvent event)
{
return PopupMenuUtils.getPopupLocation(this, event);
}
并调用 覆盖 ,以确定是否选择弹出位置处的行(或对基础组件可能有意义的任何操作):isPopupTriggeredByMouseEvent
JPopupMenu.show
JPopupMenu jPopupMenu = new JPopupMenu() {
@Override
public void show(Component invoker, int x, int y) {
int row = jList.locationToIndex(new Point(x, y));
if (row != -1 && PopupMenuUtils.isPopupTriggeredByMouseEvent((JComponent) invoker)) {
jList.setSelectedIndex(row);
}
super.show(invoker, x, y);
}
};