java:如何在jtable中只选择一个单元格而不是整行

java:如何在jtable中只选择一个单元格而不是整行,java,swing,rendering,jtable,row,Java,Swing,Rendering,Jtable,Row,在jTable中,我希望当用户单击单元格时,在屏幕上打印以下句子: I am cell in row X and column Y 其中x和Y是单击单元格的行和列。 但我得到的是:当我点击例如第1行和第4列中的单元格时 我得到以下信息: I am cell in row 1 and column 0 I am cell in row 1 and column 1 I am cell in row 1 and column 2 .... I am cell in row 1 and column

在jTable中,我希望当用户单击单元格时,在屏幕上打印以下句子:

I am cell in row X and column Y
其中x和Y是单击单元格的行和列。 但我得到的是:当我点击例如第1行和第4列中的单元格时 我得到以下信息:

I am cell in row 1 and column 0
I am cell in row 1 and column 1
I am cell in row 1 and column 2
....
I am cell in row 1 and column N  ( N = number of columns)
i、 e.选择整行

代码如下:

public class CustomTableCellRenderer extends DefaultTableCellRenderer{

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{

    Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if(isSelected) System.out.println("I am cell in row "+row+" and column "+column);



    return cell;

}
}


感谢您的帮助。

CellRenderer用于呈现单元格内容。如果要查找鼠标单击的单元格,请使用MouseListener并在mouseClicked方法中查找该单元格。

不应为此使用单元格渲染器

在表格上启用单元格选择(使用
setCellSelectionEnabled(true)
),然后获取表格的选择模型(使用
getSelectionModel()
),并在此选择模型上添加侦听器。每次触发事件时,请使用
getSelectedRow()
getSelectedColumn()
了解选择的单元格

请注意,这将为您提供所选的单元格,可以使用鼠标或键盘对其进行修改。如果您只想知道鼠标单击的位置,请查看KDM的答案。

If(isSelected)
更改为
If(isSelected&&hasFocus)
。这将仅打印选定的单元格,而不是选定的行

myTable.setRowSelectionAllowed(false);

mKorbel的答案也应该有效…

myTable.setCellSelectionEnabled(true)

是否要删除高亮显示选定的JTable行如果要限制选择仅允许单个单元格,如我所做的,则需要调用
setSelectionMode(ListSelectionModel.single_selection)也是。与
setCellSelectionEnabled(true)
结合使用,可以很好地产生所需的效果。