[英]problem when implementing a selection listener in a JTable
我正在开发具有不同行的JTable。 我想将一个事件与该表中某行的选择相关联。 我使用以下选择类为表选择提供行为:
public class TableSelectionListener implements ListSelectionListener{
public Integer item;
public TableSelectionListener(Integer item){
this.dialog = item;
}
public void valueChanged(ListSelectionEvent e) {
System.out.println("The row clicked is "+item);
}
}
当创建该表的实例sai tabletest时 ,我添加了以下代码:
tabletest.getSelectionModel().addListSelectionListener(new TableSelectionListener(tabletest.getSelectedRow());
问题是,当我单击一次行时,而不是一次检索相关消息,而是多次检索同一条消息,这表明操作重复了几次。 例如:
The row clicked is 0
The row clicked is 0
The row clicked is 0
The row clicked is 0
有人知道问题可能在哪里吗?
好吧,那很正常。
选择侦听器的创建表(值为零)使用tabletest.getSelectedRow()
的值创建。 并且,由于您从不更改侦听器中item
的值,因此该侦听器fcan结果只能显示0
。
如果我是你,我会用类似以下的方法替换valueChanged()
方法(尽管未经测试,并且我记得在混合视图和模型行值时有时会发生奇怪的事情):
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) // added as sometimes, multiple events are fired while selection changes
System.out.println("The row clicked is "+e.getFirstIndex());
}
首先,在更改选择的同时获取多个ListSelectionEvent
是完全正常的。 您可以使用getValueIsAdjusting
方法确定选择何时结束(它将返回false
)。
其次,无需使用行号构造TableSelectionListener
。 调用valueChanged
方法时,可以分别使用e.getFirstIndex()
和e.getLastIndex()
获取第一/最后选择的行的索引(请记住,除非禁用了表,否则可能选择表中的多行e.getLastIndex()
。
一种更简单的方法如下:
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
System.out.println("e...."+table.getSelectedRow());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.