【发布时间】:2017-02-17 00:05:20
【问题描述】:
我的主类是一个包含图形组件的窗口,包括JTable。
我创建了一个公共类 ContextMenu,它是 JPopupMenu 的自定义实现并包含多个 JMenuItem。
我在JTable 上注册了一个mouseListener,以便在检测到右键单击时显示ContextMenu 的实例。
问题如下:“如何根据选择的JMenuItem将选择的行传递给不同的函数?”
显而易见的答案是在我的 JMenuItem 上设置 ActionListener,但请记住 JTable 与 JPopupMenu 位于不同的类/对象中。
有些代码片段值一千字。
public class Tab implements ITab {
private ContextMenu contextMenu;
private JTable table;
private List<SomeObject> toProcess;
--- code --
private JScrollPane drawScrollTable() {
Object columns[] = {
"something",
"somethingElse"
};
Object rows[][] = {};
table = new JTable(new DefaultTableModel(rows, columns));
JScrollPane scrollPane = new JScrollPane(table);
table.setSelectionForeground(Color.BLACK);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
int selectedRow = table.rowAtPoint(e.getPoint());
if (selectedRow >= 0 && selectedRow < table.getRowCount()) {
if (!table.getSelectionModel().isSelectedIndex(selectedRow)) {
table.setRowSelectionInterval(selectedRow, selectedRow);
}
}
if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
this.show(e);
}
}
private void show(MouseEvent e){
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
return scrollPane;
}
-- code --
}
public class ContextMenu extends JPopupMenu {
JMenuItem item;
public ContextMenu(IBurpExtenderCallbacks callbacks){
this.item= new JMenuItem("item");
this.item(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do action involving the selected row, even better if possible action involving the value hold in the column 0 of the selected row and the toProcess private field
}
});
add(item);
}
}
我不知道我问的是否可行。
【问题讨论】:
-
比发布代码 sn-ps 好多了——创建并发布一个有效的minimal reproducible example,这是一个小型可编译和可运行的程序,为我们展示了您的确切的 问题。如果你能做到这一点,它将大大增加你得到一个体面答案的机会。请注意,所有代码和通信都应在您的原始问题中完成,而不是在链接中。
标签: java swing awt actionlistener actionevent