Java - JTable默认选择第一列

时间:2012-04-14 13:20:30

标签: 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 = 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);


                  }
                });

这使我:

  • 选择行时,会将列中的值传递给JTextBoxes。

但是,当我没有默认点击第一列时,选择会出现乱码。例如,如果我没有先单击“标题”列并单击“持续时间”列,它会将持续时间放在txtTitle中,其他的也会混淆。

如何添加一段代码,当选择一行时,默认选择第一列?

这是发生的事情的截图:

enter image description here

谢谢, 布赖恩

4 个答案:

答案 0 :(得分:4)

一切都取决于如何设置ListSelectionModel,但对我有用

myTable.changeSelection(row, column, false, false);

答案 1 :(得分:3)

更改此

int column = target.getSelectedColumn(); 

int column = 0; 

您的版本从用户点击的位置获取列索引,您需要第一个(索引0)

答案 2 :(得分:1)

而不是强制选择列,为什么不总是根据已知列提取值?

例如,您可以替换:

String title = listTable.getValueAt(row, column).toString();

使用:

String title = listTable.getValueAt(row, 0).toString();

如果您提供重新排序列的功能,则可以尝试table.getModel().getValueAt(convertRowIndextoModel(row), 0);

答案 3 :(得分:0)

很明显,当你点击持续时间栏

int column = target.getSelectedColumn();

获取持续时间的列值,因此

String title = listTable.getValueAt(row, column).toString();

从持续时间列中获取值。 解决这个问题的最佳方法是硬代码列号。 假设您的表符合以下顺序 标题:第0列 持续时间:第1栏 类型:第2栏等等

只需输入String title = listTable.getValueAt(row, 0).toString();

即可
String duration = listTable.getValueAt(row,1).toString(); 

依旧...... !!

希望有所帮助