在JList顶部新增的元素会自动被选中。

huangapple go评论59阅读模式
英文:

new added element in the top of JList is automatically selected

问题

创建一个使用Swing的JList,我可以显示和选择多个项目,还可以添加新元素。然而,当我选择列表的第一个元素并在顶部添加一个新元素时,我得到了两个选定的元素(旧的和新的)。但是,当我将选择模式更改为单选时,它正常工作。是否可能阻止这种自动选择,只需在多区间选择模式保持旧的选定状态?我使用了这个链接,其中包含使用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);
        jlist.setSelectionMode(
                ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        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);
    }
英文:

I am creating a JList using swing, I can display and select multiple items, also I can add a new element to it. However, when I select the first element of the list and add a new one to the top, I got two selected elements (the old one and the new one), but when I change the selection mode to single selection it works fine, is it possible to prevent this automatic selection and just keep the old one selected using multiple interval selection mode?
I used this link that contain an example using DataEventListner but I did not succeed to find a solution. Any help please?
Here is my list:

 public static void main(String args[]) {
    String labels[] = { &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot; };
    JFrame frame = new JFrame(&quot;Selecting JList&quot;);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i &lt; n; i++) {
        model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    jlist.setSelectionMode(
            ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);
    JButton jb = new JButton(&quot;add F&quot;);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, &quot;First&quot;);
        }
    });
    frame.add(jb,BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
}

答案1

得分: 2

我看到你基本上复制了你问题中的链接中的代码。那个示例仅涉及在单击“JButton”时向JList添加单个元素。它没有处理JList选择。我认为那个示例的作者没有考虑用户在单击“JButton”之前选择了一个或多个元素时会发生什么。

我能够重现你问题中描述的行为。这可能是JListListSelectionModel实现中的一个bug。我解决这个问题的方法是在actionPerformed()方法中添加代码来处理现有的JList选择。

这是我修改后的actionPerformed()方法版本。注意,其余的所有代码都没有改变。首先,我保存了所有选定行的索引。然后我清除了现有的选择。接下来,我将新元素添加到JList中。现在我需要重新选择在添加新元素之前被选中的行。但请注意,我需要将每个索引增加一,因为在索引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);
        }
    }
});
英文:

I see that you basically copied the code in the link in your question. That example only deals with adding a single element to the JList when clicking the JButton. It does not deal with the JList selection

展开收缩
. I don't think the author of that example considered what happens when the user selects one or more elements in the JList before clicking the JButton.

I was able to reproduce the behavior described in your question. It may be a bug in the implementation of JList or ListSelectionModel. The way I fixed it is to add code to method actionPerformed() that handles any existing JList selections.

Here is my modified version of method actionPerformed(). Note that all the rest of the code is unchanged. First I save the indexes of all the selected rows. Then I clear the existing selections. Then I add the new element to the JList. Now I need to re-select the rows that were selected before I added the new element. But note that I need to increment each index by one, because there is a new element at index 0 (zero).

jb.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        int[] indices = jlist.getSelectedIndices();
        jlist.getSelectionModel().clearSelection();
        model.add(0, &quot;First&quot;);
        for (int index : indices) {
            jlist.getSelectionModel().addSelectionInterval(index + 1, index + 1);
        }
    }
});

答案2

得分: 1

来自JList#setSelectionMode(int)的文档:<br/>

> ListSelectionModel.SINGLE_SELECTION - 一次只能选择一个列表索引。在此模式下,setSelectionInterval 和 addSelectionInterval 的效果相同,都将当前选择替换为由第二个参数(“引导”)表示的索引。

尝试使用 jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

英文:

From the documentation of JList#setSelectionMode(int): <br/>

> ListSelectionModel.SINGLE_SELECTION - Only one list index can be
> selected at a time. In this mode, setSelectionInterval and
> addSelectionInterval are equivalent, both replacing the current
> selection with the index represented by the second argument (the
> "lead").

try jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

答案3

得分: 0

你可以将这段代码添加到你的jb.addActionListner()中:

int x = jlist.getSelectedIndex();
jlist.clearSelection();
jlist.setSelectedIndex(x);

这样应该能够按照你的预期工作!

英文:

You can add this in your jb.addActionListner():

int x = jlist.getSelectedIndex();
    jlist.clearSelection();
    jlist.setSelectedIndex(x);

This should work just the way you want it to!

huangapple
  • 本文由 发表于 2020年5月2日 19:35:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61558723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定