我的主课是一个包含图形组件的窗口,其中包括JTable
。JTable + JPopupMenu + ActionListener =噩梦
我创建了一个公共类ContextMenu
,这是一个JPopupMenu
的自定义实现,并包含多个JMenuItem
。
我在我的JTable
上注册了一个mouseListener,在检测到右键单击时显示ContextMenu
的实例。
问题如下:“如何根据所选的JMenuItem
将选定的行传递给不同的功能?”
显而易见的答案是在我的JMenuItem
上设置ActionListener,但请记住JTable
与JPopupMenu
处于不同的类/对象。
一些代码snipet胜过千言万语。
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);
}
}
我不知道我问的是否可能。
远远高于张贴代码片段更好 - 创建和发布一个有效的[MCVE],这是一个** **小编译和执行的程序为我们详细的展示您的* *的问题。如果你能做到这一点,这将大大提高你得到一个体面的答案的机会。请注意,所有代码和通信都应在您的原始问题中完成,而不是在链接中完成。 –