sha*_*haw 6 java swing rendering row jtable
在一个jTable中,我希望当用户点击一个单元格时,这句话要打印在屏幕上:
I am cell in row X and column Y
Run Code Online (Sandbox Code Playgroud)
其中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)
Run Code Online (Sandbox Code Playgroud)
即选择整行.
这是代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
}
谢谢你的帮助.
JB *_*zet 16
您不应该为此使用单元格渲染器.
在表上启用单元格选择(使用setCellSelectionEnabled(true)),然后获取表格的选择模型(使用getSelectionModel()),并在此选择模型上添加侦听器.每次触发事件时,使用getSelectedRow()和getSelectedColumn()知道选择了哪个单元格.
请注意,这将为您提供所选单元格,可以使用鼠标或键盘进行修改.如果您只想知道鼠标点击的位置,请参阅KDM的答案.