确定单击了哪个 JTable 单元格

发布于 2024-10-13 17:45:28 字数 86 浏览 1 评论 0原文

当用户单击JTable上的单元格时,如何计算出单击的单元格的行和列?我如何在 JLabel 中显示此信息?

When a user clicks a cell on a JTable, how do I figure out the row and column of the clicked cell? How would I show this information in a JLabel?

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

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

发布评论

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

评论(5

又爬满兰若 2024-10-20 17:45:28

现有的答案有效,但如果您不启用单元格选择,还有一种替代方法可能效果更好。在您的 MouseListener 中,执行如下操作:

public void mouseClicked(java.awt.event.MouseEvent event) {
    int row = theTable.rowAtPoint(event.getPoint());
    int col = theTable.columnAtPoint(event.getPoint());
    // ...

The existing answer works, but there is an alternate method that may work better if you're not enabling cell selection. Inside your MouseListener, do something like this:

public void mouseClicked(java.awt.event.MouseEvent event) {
    int row = theTable.rowAtPoint(event.getPoint());
    int col = theTable.columnAtPoint(event.getPoint());
    // ...
倾城花音 2024-10-20 17:45:28

您可以在 JTable 上使用以下方法来检索所选单元格的行和列:

int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();

并向表添加一个 SelectionListener 以捕获选择表时的事件。

You can use following methods on JTable to retrieve row and column of the selected cell:

int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();

And add a SelectionListener to table to catch the event when the table is selected.

吝吻 2024-10-20 17:45:28

它对我有用!

jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
 public void mouseClicked(java.awt.event.MouseEvent evt) {
    int row = jTable1.rowAtPoint(evt.getPoint());
    int col = jTable1.columnAtPoint(evt.getPoint());
    if (row >= 0 && col >= 0) {


    }
 }
});

It is working for me!!!

jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
 public void mouseClicked(java.awt.event.MouseEvent evt) {
    int row = jTable1.rowAtPoint(evt.getPoint());
    int col = jTable1.columnAtPoint(evt.getPoint());
    if (row >= 0 && col >= 0) {


    }
 }
});
天气好吗我好吗 2024-10-20 17:45:28

你尝试过addMouseListener()吗?我希望您正在使用 Swing 的 JTable。

did you try addMouseListener()? I hope you are about using Swing's JTable.

2024-10-20 17:45:28

我发现当列被隐藏/重新排序时 columnAtPoint 返回可见的列索引,这不是我需要的。对我有用的代码是

int row = theTable.convertRowIndexToModel(theTable.rowAtPoint(event.getPoint()));
int col = theTable.convertColumnIndexToModel(theTable.columnAtPoint(event.getPoint()));

I've found that when columns are hidden/reordered columnAtPoint returns the visible column index, which isn't what I needed. Code which worked for me is

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