SilentCoder
SilentCoder

Reputation: 47

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 !!

Upvotes: 0

Views: 3654

Answers (1)

dic19
dic19

Reputation: 17971

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.

Upvotes: 1

Related Questions