Java JLabel 或 JTable 单元格上的 ActionListener

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1378096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:21:00  来源:igfitidea点击:

ActionListener on JLabel or JTable cell

javaswingjtablemouseeventactionlistener

提问by stefita

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?

我有一个带有JLabel[][]as 数据的 JTable 。现在我想检测对 JLabel 或表格单元格(但仅在其中一列中)的双击。如何分别在 JLabel 表格单元格上添加 Action/MouseListener?

采纳答案by Vinay Sajip

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
    }
  }
});

回答by camickr

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.

a) 你应该处理 mousePressed,而不是 mouseClicked。只有在同一像素位置生成 mousePressed 和 mouseReleased 事件时才会触发 mouseClicked 事件。如果用户在双击时将鼠标移动 1 个像素,您将不会获得预期的双击。

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.

b) 此外,您可能还需要考虑使用 columnAtPoint() 和 rowAtPoint() 方法来获取单击的单元格。虽然在这种情况下它可能没有什么不同,但如果您尝试使用 MouseListener 进行鼠标右键单击,这将很重要,因为选择没有改变。所以如果你养成了使用这种方法的习惯,你以后就不会有问题了。