在 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)
即选择整行。
这是代码:
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;
}
}
谢谢你的帮助。
您不应该为此使用单元格渲染器。
在表格上启用单元格选择(使用setCellSelectionEnabled(true)
),然后得到表的选择模型(使用getSelectionModel()
),并在此选择模型上添加一个侦听器。每次触发事件时,使用getSelectedRow()
and getSelectedColumn()
知道选择了哪个单元格。
请注意,这将为您提供选定的单元格,可以使用鼠标或键盘对其进行修改。如果您只想知道鼠标点击的位置,请参阅 KDM 的答案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)