我已经创建了以下实现ListSelectionListener接口的类。这个类应该“监听”我创建的JList的选择事件。每当用户单击此列表中的某一行时,应更新selected_row值并显示字符串"The format row selected is ....“因此应该有所改变。但是,在多次单击这些行之后,select_row值不会改变。有没有人能给我一个解释,希望能做我想做的事?提前感谢!!
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import ee.dobax.portal.CommonPath;
public class FormatListSelectionListener implements ListSelectionListener{
public ContentGenerated content;
private CommonPathList path_list;
private ConfigRenderingDialog dialog;
public FormatListSelectionListener(ConfigRenderingDialog dialog){
content = dialog.content;
path_list = dialog.pathList;
}
public void valueChanged(ListSelectionEvent e) {
int selected_row;
if(e.getValueIsAdjusting() == false){
selected_row = e.getLastIndex();
System.out.println("The format row selected is "+selected_row);
path_list.addFormatListRowSelected(selected_row);
List<CommonPath> list_p = content.getPathList(selected_row);
Object[] path_list_to_array = new Object[list_p.size()];
path_list.getContents().removeAllElements();
for(int x = 0; x < list_p.size(); x++){
path_list_to_array[x] = list_p.get(x);
path_list.getContents().addElement(path_list_to_array[x]);
}
}
}
} 发布于 2010-09-28 20:49:42
我在阅读文档时发现,ListSelectionEvent只告诉您firstIndex和lastIndex之间的选择发生了更改,而不是在哪个方向上更改。一旦知道发生了更改(已经触发了ListSelectionEvent ),就可以从JList中读取当前选定的值
selected_row = ((JList) e.getSource()).getSelectedIndex();您需要检查selected_row是否是非负的,以防用户操作只是取消选择唯一选中的选项。
发布于 2010-09-28 20:53:12
你能分享一下在JList上附加这个监听器的代码吗?它应该是这样的:
list = new JList(listData);
listSelectionModel = list.getSelectionModel();
listSelectionModel.addListSelectionListener(
new FormatListSelectionListener());请参阅How to write ListSelection Listener
发布于 2010-09-28 20:47:59
您不想检查e.getValueIsAdjusting()是否为真吗?因为这应该意味着事件发生了变化。这可能就是为什么它只工作一次(第一次可能没有变化),之后就不起作用了。
另外,我将其改为if(e.getValueIsAdjusting()),因为它返回一个布尔值。
https://stackoverflow.com/questions/3812744
复制相似问题