【问题标题】:valueChanged in ListSelectionListener not workingListSelectionListener 中的 valueChanged 不起作用
【发布时间】:2011-04-18 06:50:02
【问题描述】:

我创建了以下实现 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]);
            }

        }
  }


 }   

【问题讨论】:

    标签: java swing jlist


    【解决方案1】:

    您不想检查 e.getValueIsAdjusting() 是否为真吗?因为那应该意味着事件发生了变化。这可能是它工作一次(第一次可能没有变化)然后就不起作用的原因。

    我也要把它改成 if(e.getValueIsAdjusting()) 因为它返回一个布尔值。

    【讨论】:

      【解决方案2】:

      我读到的文档表明ListSelectionEvent 仅告诉您firstIndexlastIndex 之间的选择已更改,但未更改方向。一旦您知道发生了更改(ListSelectionEvent 已被触发),您就可以从 JList 中读取当前选定的值:

      selected_row = ((JList) e.getSource()).getSelectedIndex();
      

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

      【讨论】:

      • @Tony:那么你确定某些东西确实被选中了吗?
      • 是的,在 FormatList 构造函数类中我有 this.setSelectedIndex(0);
      • @Tony:你是什么意思它没有检索到任何东西?该方法返回一个int,你得到什么值?
      【解决方案3】:

      您能否分享将此侦听器附加到 JList 的代码? 它应该是这样的:

      list = new JList(listData);
      listSelectionModel = list.getSelectionModel();
      listSelectionModel.addListSelectionListener(
               new FormatListSelectionListener());
      

      How to write ListSelection Listener

      【讨论】:

      • 是的,差不多就是这样:ListSelectionModel listSelectionModel = this.getSelectionModel(); listSelectionModel.addListSelectionListener(new FormatListSelectionListener(dialog));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 2012-02-14
      • 1970-01-01
      • 2012-07-09
      • 2013-09-25
      • 2015-05-12
      • 2019-06-29
      相关资源
      最近更新 更多