el siguiente código es para crear un menú de click derecho para un JTable.
Se usarán dos métodos, uno para hacer el menú en sí y el otro para añadir los ítems (u opciones).
Código:
Código: Seleccionar todo
private void tableMenu(final JTable table) {
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
int r = table.rowAtPoint(e.getPoint());
if (r >= 0 && r < table.getRowCount()) {
table.setRowSelectionInterval(r, r);
} else {
table.clearSelection();
}
int rowindex = table.getSelectedRow();
if (rowindex < 0) {
return;
}
if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
JPopupMenu popup = tablePopup(table, rowindex);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
Código: Seleccionar todo
private JPopupMenu tablePopup(final JTable table, final int row) {
JPopupMenu popup = new JPopupMenu("Popup");
JMenuItem refreshItem = new JMenuItem("Select");
refreshItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Nombre: "+table.getValueAt(row, 0));
System.out.println("Apellido: "+table.getValueAt(row, 1));
System.out.println("Edad: "+table.getValueAt(row, 2));
}
});
popup.add(refreshItem);
return popup;
}
Código: Seleccionar todo
public NewJFrame() { //Constructor del Frame
initComponents();
tableMenu(jTable1); //Debe ir después del 'initComponents();' sí o sí
}
