简体   繁体   English

确定单击哪个JTable单元

[英]Determine Which JTable Cell is Clicked

When a user clicks a cell on a JTable , how do I figure out the row and column of the clicked cell? 当用户单击JTable上的单元格时,如何计算单击单元格的行和列? How would I show this information in a JLabel ? 我如何在JLabel显示此信息?

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: MouseListener ,执行以下操作:

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

You can use following methods on JTable to retrieve row and column of the selected cell: 您可以在JTable上使用以下方法来检索所选单元格的行和列:

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

And add a SelectionListener to table to catch the event when the table is selected. 并在表中添加SelectionListener以在SelectionListener表时捕获事件。

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) {


    }
 }
});

I've found that when columns are hidden/reordered columnAtPoint returns the visible column index, which isn't what I needed. 我发现当列被隐藏/重新排序时, columnAtPoint返回可见列索引,这不是我需要的。 Code which worked for me is 对我有用的代码是

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

did you try addMouseListener() ? 你尝试过addMouseListener()吗? I hope you are about using Swing's JTable. 我希望你是关于使用Swing的JTable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM