我这里有一个小场景,可能是重复的。我有 JTable,可以在其中显示一些数据,我有一个鼠标监听器,可以监听表格上的右键单击并显示带有一个菜单项的弹出菜单。我的目标是,当用户单击菜单项时,我从表中获取值并将它们输入到一个自定义对话框中,该对话框中有一些填充字段,这样用户就不必手动输入整个对话框,因为我将将表格中选择的值提供给对话框。但我的问题是 menuitem actionevent 没有办法获取要点,以便我可以使用 table.getRowAt() 。我读过另一条评论(查看此处 https://stackoverflow.com/a/4122082/1788917 ),其中我被告知可以将行号保存在变量中,然后可以由菜单项的 Action 监听器访问该变量。
我希望它看起来像这样
theScrollPane.getViewport().add(myJTable, null);
JMenuItem menuItem = new JMenuItem(clickMe);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuItemActionPerformed(e);
}
});
MouseListener popupListener = new PopupListener();
popupMenu.add(menuItem);
myJTable.addMouseListener(popupListener);
protected void menuItemActionPerformed (ActionEvent e) {
// what to do here to get the table row data
// and send it to my custom dialog via it's constructor ???
}
// a simple nested class for the popup
class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
int row = myJTable.rowAtPoint(e.getPoint());
int selectedRow = myJTable.getSelectedRow();
// just to make sure the popup appears only where the row is
// selected
if (row == selectedRow) {
showPopup(e);
}
}
public void mouseReleased(MouseEvent e) {
int row = myJTable.rowAtPoint(e.getPoint());
int selectedRow = myJTable.getSelectedRow();
if (row == selectedRow) {
showPopup(e);
}
}
private void showPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
所以我的问题是,保存行号是我可以做到这一点的唯一方法还是有更好的方法?
最佳答案
i have read another comment (check here https://stackoverflow.com/a/4122082/1788917) where i have been told that i can save the row number in a variable
您读错了评论。
如果您阅读该链接上方的答案(即获得 7 票的链接),您将看到解决方案是在显示弹出菜单之前选择您单击的行。然后在您的菜单项 Action 中您可以引用
table.getSelectedRow();
关于java:从popupmenu actionListener事件获取行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15657734/