Search code examples
javaswingjcomboboxjlist

Jlist is not getting updated when an action performed by selecting an item in Combobox


I am trying to perform action by selecting a value in Combobox and after selection, based of the value selected Jlist should be updated. But list is taking value only first time but its not getting updated while changing the values. However Values are coming and action is performed as I can see values are coming in consol.My code is as follows:

ArrayList< String> ModuleNames = GetModuleNames();
String[] ModuleNames1 = ModuleNames.toArray(new String[ModuleNames.size()]);    
comboModuleName = new JComboBox(ModuleNames1);
comboModuleName.setEditable(true);
comboModuleName.setSelectedItem(null);
comboModuleName.setBounds(280,80,350,40);
panel.add(comboModuleName);

comboModuleName.addActionListener(new ActionListener() {

    @SuppressWarnings("unchecked")
    @Override
    public void actionPerformed(ActionEvent e) {
    String currentSelectedValue = comboModuleName.getSelectedItem().toString();
    System.out.println("selected value is "+currentSelectedValue);
    try 
    {   //collecting values from a function and want to populate in the list,currentSelectedValue

        //currentSelectedValue is the value selected in the combobox based on this value function                      //returns some values as a arraylist
        ArrayList CurrentModuleFunctions = getFunctionAndParametereNames(currentSelectedValue);
        Vector reflectedValues = new Vector();

        for (int i = 0; i < CurrentModuleFunctions.size(); i++) {
            reflectedValues.addElement(CurrentModuleFunctions.get(i));
        }
        if(e.getSource() == comboModuleName) {  
            listFunctionNames = new JList(reflectedValues); 
            listFunctionNames.setBounds(280,140,350,140);
            panel.add(listFunctionNames);
        }
    } 
    catch (ClassNotFoundException | IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    }
});

I am not sure why Jlist is not getting updated as I can get the values when I am selecting new value in combobox.


Solution

  • Instead of creating the JList inside actionPerformed() method,create it outside

        listFunctionNames = new JList();
        listFunctionNames.setBounds(280,140,350,140);
        panel.add(listFunctionNames);
    

    and inside actionPerformed(),just set the values

    listFunctionNames.setListData(reflectedValues);