ActionListener on JLabel or JTable cell
Asked Answered
J

3

25

I have a JTable with JLabel[][] as data. Now I want to detect a double click on either the JLabel or a table cell (but only in one of the columns). How can I add an Action/MouseListener on JLabel respectively table cell?

Jairia answered 4/9, 2009 at 9:9 Comment(1)
JLabels haven´t ActionListeners, but has MouseListener, add them and listen on mouseClickSrinagar
G
68

How about:

table.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent e) {
    if (e.getClickCount() == 2) {
      JTable target = (JTable)e.getSource();
      int row = target.getSelectedRow();
      int column = target.getSelectedColumn();
      // do some action if appropriate column
    }
  }
});
Gorky answered 4/9, 2009 at 9:16 Comment(2)
if i have that Jlabel inside Table cell then how will i call that click event on click?Crews
as below @Camickr comment, I think it's better to use MousePressed method not MouseClickTightrope
P
28

Basically the same suggestion as the one already accepted except:

a) you should handle mousePressed, not mouseClicked. A mouseClicked event is only fired when a mousePressed and mouseReleased event is generated at the same pixel location. You if the user moves the mouse even 1 pixel while double clicking you will not get the expected double click.

b) Also you may want to consider using the columnAtPoint() and rowAtPoint() methods to get the clicked cell. Although it probably doesn't make a difference in this case, it will matter if you ever try to use a MouseListener for right mouse clicks, since the selection isn't changed. So if you get in the habit of using this method you won't have problems in the future.

Prehension answered 4/9, 2009 at 23:26 Comment(0)
G
0

as @camickr said in option b you should use columnAtPoint() otherwise you can get unintended behaviour when clicking outside a cell but inside the table.

Gunk answered 19/8, 2022 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.