Right-click MouseListener on whole JTable component

1.7k Views Asked by At

I'm using Netbeans and I've designed a window with JTable and added MouseEvent listener on JTable component and added this code:

private void productsTableMousePressed(java.awt.event.MouseEvent evt) {
    if(evt.isPopupTrigger()) {
        tablePopupMenu.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
        tablePopupMenu.setVisible(true);
        System.out.println("Fired!");
    }
}

private void productsTableMouseReleased(java.awt.event.MouseEvent evt) {
    if(evt.isPopupTrigger()) {
        tablePopupMenu.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
        tablePopupMenu.setVisible(true);
    }
}

But it works only when I click on some cells. I want to get it working on whole JTable area. How?

3

There are 3 best solutions below

2
On BEST ANSWER

Assuming your table is inside a JScrollPane, it may not cover the entire viewport. To ensure the whole area of your viewport is covered, call setFillsViewportHeight(true) on your table.

1
On

But it works only when I click on some cells, but i want to get it working on whole JTable area

The MouseListener will work on all cells. I don't know if you should be using the setLocation(...) method.

See Bringing Up a Popup Menu for example code.

Or a better approach is to use:

table.setComponentPopupMenu(...);
0
On

I've found that in my JTable (which is in a JScrollPane, nested in a JInternalFrame), there can be issues with scrolling and resizing when the JTable was larger than the JScrollPane.

Basically, if the Frame is on my left monitor, but I've scrolled the table all the way to the right, the pop-up appears on my right monitor.

I reviewed the results of four different options: the getMousePositions() for both the frame and the scroll pane, plus the mouse event getX and getXOnScreen().

The only one that gave me the results I wanted was the getMousePositions() for the frame. Everything else was offset by it's own internal view of the world, which makes sense to me.

So I guess what I'm saying is be careful where you get your mouse coordinates.