Search code examples
javaswingjtablemouseevent

JTable right click mouse ActionListener doesn't return correct row and column values


I have this piece of code that detects a right click on a JTable:

jt.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if(e.getButton() == MouseEvent.BUTTON3) {
            JTable target = (JTable)e.getSource();
            int row = target.getSelectedRow();
            int column = target.getSelectedColumn();
            System.out.println(row + column);
            System.out.println(column);
            System.out.println("right click!");
        }
    }
});

I need the row and column values for the system to figure out the contents of the cell being clicked so that I can run functions and stuff, but for my current table jt: enter image description here

When I right click on any cell in the row, it returns "right click!" (which is correct) and "-2 -1" for the row and column values. Given that they are in different columns of the table, the row and column values should be positive, and the column values should be different. I'm not understanding what's happening here that made this code not work.

Note: previously I had the if (e.getClickCount() == 2) { do stuff } before changing it to the right click function and it worked fine - returned the correct rows and columns.


Solution

  • A right click on a table will not select anything.

    This is what happens if I right click anywhere in the table as soon as the GUI appears.

    enter image description here

    Whereas this is what I see after left clicking in the middle column of the first row, then right click anywhere in the table:

    enter image description here

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    
    public class TableSelectionWithMouse {
    
        private JComponent ui = null;
        String[] headers = {"First Name", "Last Name", "Occupation"};
        String[][] data = {
            {"Yohan", "Jones", "Mouse Wrangler"},
            {"Lucy", "Yang", "Emeritus Professor of Phlogiston"}
        };
        JLabel output = new JLabel("Right click to do .. stuff");
    
        TableSelectionWithMouse() {
            initUI();
        }
    
        public void initUI() {
            if (ui != null) {
                return;
            }
    
            ui = new JPanel(new BorderLayout(4, 4));
            ui.setBorder(new EmptyBorder(4, 4, 4, 4));
    
            final JTable table = new JTable(data, headers);
            ui.add(new JScrollPane(table));
            ui.add(output, BorderLayout.PAGE_END);
            MouseListener mouseListener = new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println(".mouseClicked()" + e);
                    if (e.getButton() == MouseEvent.BUTTON3) {
                        JTable target = (JTable) e.getSource();
                        int row = target.getSelectedRow();
                        int column = target.getSelectedColumn();
                        output.setText(String.format("Row: %1s Col: %1s", row, column));
                    }
                }
            };
            table.addMouseListener(mouseListener);
        }
    
        public JComponent getUI() {
            return ui;
        }
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception useDefault) {
                    }
                    TableSelectionWithMouse o = new TableSelectionWithMouse();
    
                    JFrame f = new JFrame(o.getClass().getSimpleName());
                    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    f.setLocationByPlatform(true);
    
                    f.setContentPane(o.getUI());
                    f.pack();
                    f.setMinimumSize(f.getSize());
    
                    f.setVisible(true);
                }
            };
            SwingUtilities.invokeLater(r);
        }
    }