JLabel 或 JTable 单元格上的 ActionListener

发布于 2024-08-03 09:25:14 字数 132 浏览 6 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小…红帽 2024-08-10 09:25:14

怎么样:

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

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
    }
  }
});
梦途 2024-08-10 09:25:14

基本上与已经接受的建议相同,除了:

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

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

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.

你又不是我 2024-08-10 09:25:14

正如@camickr 在选项 b 中所说
您应该使用columnAtPoint(),否则在单元格外部但在表格内部单击时可能会出现意外行为。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文