将自动选择JList顶部的新添加元素

问题描述 投票:1回答:2

我正在使用swing创建一个JList,我可以显示和选择多个项目,也可以向其中添加一个新元素。但是,当我选择列表中的第一个元素并在顶部添加一个新元素时,我得到了两个选定元素(旧元素和新元素),是否有可能阻止这种自动选择而只让旧元素被选中?我使用了此link,其中包含使用DataEventListner的示例,但未成功找到解决方案。有什么帮助吗?这是我的清单:

 public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H" };
    JFrame frame = new JFrame("Selecting JList");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);
    JButton jb = new JButton("add F");
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, "First");
        }
    });
    frame.add(jb,BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
}
java swing jlist
2个回答
0
投票

摘自JList#setSelectionMode(int)的文档:

ListSelectionModel.SINGLE_SELECTION-只能有一个列表索引一次选择。在此模式下,setSelectionInterval和addSelectionInterval是等效的,都替换了当前带有第二个参数表示的索引的选择(“线索”)。

尝试jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


0
投票

[我看到您基本上将问题中的代码复制到了link中。该示例仅涉及在单击JList时将单个元素添加到JButton。它不处理JList选择。我认为该示例的作者没有考虑过当用户在JList中选择一个或多个元素之前单击JButton时会发生什么。

我能够重现您的问题中描述的行为。在执行JListListSelectionModel时可能是一个错误。我解决的方法是向方法actionPerformed()中添加代码,以处理任何现有的JList选择。

这是我修改的方法actionPerformed()。请注意,其余所有代码均未更改。首先,我保存所有选定行的索引。然后,我清除现有选择。然后,将新元素添加到JList。现在,我需要重新选择在添加新元素之前选择的行。但是请注意,我需要将每个索引加1,因为索引0(零)处有一个新元素。

jb.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        int[] indices = jlist.getSelectedIndices();
        jlist.getSelectionModel().clearSelection();
        model.add(0, "First");
        for (int index : indices) {
            jlist.getSelectionModel().addSelectionInterval(index + 1, index + 1);
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.