简体   繁体   中英

Getting selected Items from Jlist

I have seen many posts & tried different ways to solve this problem but still I dont get my list of selected items. Here's the code which I use.

public List<String> getSelectedDeviceList()
    {
        return list;
    }
    /**
     * Create the frame.
     */
    public JLogicDesign(Frame frame, List<String> listDevices) {

        super();
        setTitle("Device Names");

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 331, 316);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        jlistModel = new DefaultListModel(); 
        for(String s: listDevices)
        {
            jlistModel.addElement(s);
        }

        final JList jlist = new JList(jlistModel);
        jlist.setVisibleRowCount(5);
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);


        btnOk = new JButton("OK");      
        btnOk.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {                   

                    list = new ArrayList<String>();
                    Object[] values = jlist.getSelectedValues();
                    for(Object o: values)
                    {
                        list.add(o.toString());
                    }               
                dispose();
            }
        });

The JList is being properly populated. When I try to get the selected Items, I get a NPE.

This is another class where I'm calling the above class

JLogicDesign jld = new JLogicDesign(f,listOfDevices);           

            devices = new ArrayList<String>();
            devices = jld.getSelectedDeviceList();

Thanks in advance !!

You get NPE at this line:

JLogicDesign jld = new JLogicDesign(f,listOfDevices);
devices = new ArrayList<String>();
devices = jld.getSelectedDeviceList(); // NPE here

Because list variable in JLogicDesign is only initialized when btnOk is pressed. So the pointed line is executed before this button is pressed and that's why it throws NPE.

To avoid NPE you shoud initialize list in JLogicDesign . However it doesn't solve the problem. You wont get NPE but you'll get an empty list. This is because JLogicDesign is not modal and even if these sentences are being executed on the Event Dispatch Thread jld.getSelectedDeviceList() will return the list before btnOk is pressed.

If you need the selected devices before continue then consider use a modal JDialog .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM