ListSelectionListener 中的 valueChanged 不起作用

Ant*_*nto 3 java swing jlist

我创建了以下实现 ListSelectionListener 接口的类。这个类应该“监听”我创建的 JList 的选择事件。每次用户单击此列表的一行时,都应更新 selected_row 值,因此应更改字符串“所选的格式行是 ....”。但是,多次单击行后, 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]);
            }

        }
  }


 }   
Run Code Online (Sandbox Code Playgroud)

Mar*_*iot 5

我阅读了文档,表明 the ListSelectionEventonly 告诉您firstIndex和之间的选择lastIndex发生了变化,但没有告诉您在哪个方向。一旦您知道发生了更改(aListSelectionEvent已被触发),您就可以从以下位置读取当前选定的值JList

selected_row = ((JList) e.getSource()).getSelectedIndex();
Run Code Online (Sandbox Code Playgroud)

您需要检查selected_row是否为非负值,以防用户操作只是取消选择唯一选定的选项。