Carlo del Mundo Carlo del Mundo - 1 year ago 75
Java Question

Java Swing JTable; Right Click Menu (How do I get it to "select" aka highlight the row)

Short: I need a "right-click event" to highlight the cell row.

I am using a JTable inside a ScrollPane in Java Swing (Netbeans Matisse). I have a MouseClicked event listener on the JTable that does the following:

if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
System.out.println("Right Click");, evt.getX(), evt.getY())

The problem is... whenever I execute a right click on the JTable, the row isn't highlighted (I set the selection to rows only btw). I have looked for several setSelected() functions but could not find a suitable one. By default, left clicking automatically highlights the row. How do I set it up for right clicks?

Answer Source

like this:

table.addMouseListener(new MouseAdapter() {
    public void mouseReleased(MouseEvent e) {
        int r = table.rowAtPoint(e.getPoint());
        if (r >= 0 && r < table.getRowCount()) {
            table.setRowSelectionInterval(r, r);
        } else {

        int rowindex = table.getSelectedRow();
        if (rowindex < 0)
        if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) {
            JPopupMenu popup = createYourPopUp();
  , e.getX(), e.getY());