Java-JTable默认情况下选择第一列
我有一段代码:Java-JTable默认情况下选择第一列,java,swing,jtable,selection,mouselistener,Java,Swing,Jtable,Selection,Mouselistener,我有一段代码: listTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { JTable target = (JTable)e.getSource(); int row = t
listTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
int column = target.getSelectedColumn();
String title = listTable.getValueAt(row, column).toString();
String duration = listTable.getValueAt(row, column+1).toString();
String genre = listTable.getValueAt(row, column+2).toString();
String actor = listTable.getValueAt(row, column+3).toString();
String director = listTable.getValueAt(row, column+4).toString();
//String rentable = listTable.getValueAt(row, column+5).toString();
//String synopsis = listTable.getValueAt(row, column+6).toString();
txtTitle.setText(title);
txtDuration.setText(duration);
txtGenre.setText(genre);
}
});
这使我能够:
选中一行后,它会将列中的值传递给JTextBox。
但是,默认情况下,当我没有单击第一列时,选择会变得混乱。例如,如果我不先单击Title列,然后单击Duration列,它会将Duration放在txtTitle中,其他的也会混淆
如何添加一段代码,当选择一行时,它默认选择第一列
这是发生的情况的屏幕截图:
谢谢,
布莱恩改变这个
int column = target.getSelectedColumn();
到
您的版本从用户单击的位置获取列索引,您需要第一个索引0一切都取决于如何设置ListSelectionModel,但对我来说是有效的
myTable.changeSelection(row, column, false, false);
与其强制选择列,为什么不总是基于已知列提取值 例如,您可以替换:
String title = listTable.getValueAt(row, column).toString();
与:
如果您提供了对列重新排序的功能,则可以改为尝试table.getModel.getValueAtconvertRowIndextoModelrow,0 这是显而易见的,就像你点击持续时间列一样 int column=target.getSelectedColumn 获取持续时间的列值,因此
String title = listTable.getValueAt(row, column).toString();
从duration列获取值。。
解决这一问题的最佳方法是硬代码第1列。
假设您的桌子是按以下顺序排列的
标题:第0列
持续时间:第1栏
类型:第二栏等等
简单地把字符串title=listTable.getValueAtrow,0.toString
等等
希望能有所帮助谢谢!我知道这很简单!如果列被拖向四周,则需要使用模型的getValueAt,请查看我的答案。
String title = listTable.getValueAt(row, 0).toString();
String title = listTable.getValueAt(row, column).toString();
String duration = listTable.getValueAt(row,1).toString();