5

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?

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188

3 Answers3

3

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(...);
camickr
  • 321,443
  • 19
  • 166
  • 288
3

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.

jackrabbit
  • 5,525
  • 1
  • 27
  • 38
  • Yes, you are right, that was my problem :) I figured it out few moments ago. But, thank you for this method because i solved it triggering mousePressed on JScrollPane, but your solutions sounds better. – Mikołaj Stolarski Jan 18 '12 at 12:38
  • Not many people seem to know how to interact with a JScrollPane properly. I myself am still struggling with it more than I'd like. – jackrabbit Jan 18 '12 at 17:52
0

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.