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

user402642 picture user402642 · Aug 24, 2010 · Viewed 45k times · Source

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");
          JPopUpMenu.show(myJTable, 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

clamp picture clamp · Aug 24, 2010

like this:

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 = createYourPopUp();
            popup.show(e.getComponent(), e.getX(), e.getY());
        }
    }
});

......