2

I have a jlist which has some elements and works properly. Then I am trying to add the selected jlist elements to string list, but it wont show any results (no errors though). Whats wrong?

inal JList list = new JList(arraylist.toArray());
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

JOptionPane.showMessageDialog(
                null, list, "Select", JOptionPane.QUESTION_MESSAGE);

ListSelectionListener listSelectionListener = new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {

        String lstr = list.getSelectedValue().toString();
        List<String> tolist = Arrays.asList(lstr);

        System.out.println(tolist);
    }
};

Updated: ( Fixed)

                       final ListSelectionListener listSelectionListener = new ListSelectionListener() {
                       public void valueChanged (ListSelectionEvent e) { 



                           String lstr = list.getSelectedValuesList().toString();
                           System.out.println(lstr);
                           List<String> tolist = Arrays.asList(lstr);
                           System.out.println(tolist);

                       }
                       };

                       list.addListSelectionListener(listSelectionListener);

JOptionPane.showMessageDialog( null, list, "Select", JOptionPane.QUESTION_MESSAGE);

4

2 回答 2

3

在声明匿名内部类之后向ListSelectionListener您注册您的JList

ListSelectionListener listSelectionListener = new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
           // ...
    }
};
list.addListSelectionListener(listSelectionListener);

阅读:如何编写列表选择侦听器

于 2013-10-03T02:14:05.827 回答
2

如果您使用多项选择,为什么要使用 getSelectedValue 而不是 getSelectedValues 或(对于 JDK 7)getSelectedValuesList?

于 2013-10-03T02:09:52.667 回答