Ram*_*amo 4 java swing jtable jpopupmenu
我有一种情况,我在右键单击JTable时创建了一个弹出菜单.创建弹出菜单的标准方法:
aJTable.setComponentPopupMenu(rightClickMenu);
Run Code Online (Sandbox Code Playgroud)
之后在注册的操作中,我无法找到右键单击哪个单元格以显示该弹出菜单.
rightClickMenuItem.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Work out what cell was right clicked to generate the menu
}
});
Run Code Online (Sandbox Code Playgroud)
关于你如何做到这一点的任何想法?
令人惊讶的事实是:安装了componentPopupMenu后,mouseListener永远不会看到作为popupTrigger的mouseEvent(原因是显示componentPopup由BasicLookAndFeel安装的AWTEventListener全局处理,并且该侦听器使用该事件).
看到该触发器的mousePosition的唯一地方是getPopupLocation(MouseEvent),因此获取它的唯一可靠方法(用于执行依赖于位置的配置/操作)是@Mad的建议,即重写该方法并将值存储在某处以后用.
下面的代码段使用clientProperty作为存储位置:
final JTable table = new JTable(new AncientSwingTeam()) {
@Override
public Point getPopupLocation(MouseEvent event) {
setPopupTriggerLocation(event);
return super.getPopupLocation(event);
}
protected void setPopupTriggerLocation(MouseEvent event) {
putClientProperty("popupTriggerLocation",
event != null ? event.getPoint() : null);
}
};
JPopupMenu popup = new JPopupMenu();
Action action = new AbstractAction("show trigger location") {
@Override
public void actionPerformed(ActionEvent e) {
JPopupMenu parent = (JPopupMenu) SwingUtilities.getAncestorOfClass(
JPopupMenu.class, (Component) e.getSource());
JTable invoker = (JTable) parent.getInvoker();
Point p = (Point) invoker.getClientProperty("popupTriggerLocation");
String output = p != null ? "row/col: "
+ invoker.rowAtPoint(p) + "/" + invoker.columnAtPoint(p) : null;
System.out.println(output);
}
};
popup.add(action);
popup.add("dummy2");
table.setComponentPopupMenu(popup);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3117 次 |
最近记录: |