如果您想继续使用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);
请注意,当您的弹出窗口通过键盘调用(且您未覆盖目标组件上的
getPopupLocation
)时,在
JPopupMenu.show
中获取的x、y位置将是您组件的中点。在这种情况下,如果已经有选择,您可能不想更改选择。
我提出的解决键盘与鼠标调用问题的方法是,在
getPopupLocation
的覆盖中在组件上设置客户端属性,然后在显示弹出窗口时进行检查。通过键盘调用时,
getPopupLocation
的参数将为
null
。下面是核心代码(也许可以实现在可用于您组件及其弹出菜单的实用程序类中)。
private static final String POPUP_TRIGGERED_BY_MOUSE_EVENT = "popupTriggeredByMouseEvent";
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);
}
重写JPopupMenu.show
方法并调用isPopupTriggeredByMouseEvent
来确定是否选择弹出位置上的行(或对于基础组件可能有意义的任何动作):
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);
}
};
if(e.getButton() == MouseEvent.BUTTON3)
而不是if(e.isPopupTrigger())
,原因非常简单,触发方法对我总是返回 false。否则我的代码将完全与 @jmendeth +1 相同。 - Borotable.setComponentPopupMenu(popup);
,因此在释放时没有触发。所以在 Wins 上你也需要释放。知道这点很好 :) - BorosetComponentPopupMenu
ж„Ҹе‘ізқҖжӮЁе°Ҷж— жі•йҖҡиҝҮй”®зӣҳи°ғз”Ёеј№еҮәиҸңеҚ•гҖӮ - Rangi KeenJPopupMenu
更加清晰地完成。 - Alba Mendez