我在JTable的应用程序中使用JPopupMenu:
public FilePopupMenu(JTable table) {
super();
this.table = table;
// Open File
JMenuItem open = new JMenuItem("Open file");
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
open.addActionListener((ActionEvent e) -> {
try {
FileUtils.openFileInNotepad(FileUtils.buildXmlFilePath(selectedRow));
} catch (MyException e1) {
LOG.error("Error when opening file : " + selectedRow, e1);
}
});
this.add(open);
this.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
FilePopupMenu popup = (FilePopupMenu) e.getSource();
int rowAtPoint = popup.getTable()
.rowAtPoint(SwingUtilities.convertPoint(popup, new Point(0,0), popup.getTable()));
if (rowAtPoint > -1) {
popup.getTable().setRowSelectionInterval(rowAtPoint, rowAtPoint);
@SuppressWarnings("unchecked")
Vector<String> selectedRow = (Vector<String>) ((FilePanelModel) popup.getTable()
.getModel()).getDataVector()
.get(popup.getTable().getRowSorter().convertRowIndexToModel(rowAtPoint));
popup.setSelectedRow(selectedRow);
}
}
});
}
});
}
我向其中每个添加了带有Accelerator的JMenuItem。
但是,当弹出菜单不可见时,这些加速器不起作用。
我尝试使用按键侦听器打开菜单,但它显示在屏幕的左上方,并且无法关闭:
JPopupMenu popup = new FilePopupMenu(tableFiles);
tableFiles.setComponentPopupMenu(popup);
tableFiles.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
popup.setVisible(true);
}
}
});
我正在考虑创建JMenu,然后将其添加到菜单栏中以使其正常工作。
还有其他想法吗?