Question

Hi there I need urgent help on populating the second Jlist, I have successfully populated the first from a DB but an having huge difficulty in finding a way to populate the second.

I would like to,

get selected from Jlist1, click button, add selected to Jlist2

My code, add the selected to Jlist2 but when I select a new value from Jlist1 and click the button it replaces the existing value in Jlist2 which I don't want. I want it to add to the list not write over it.

private void butCounter1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        String selec =(String) LCandidate.getSelectedValue();
        DefaultListModel def = new DefaultListModel();
        def.addElement(selec);

        Lmyvotes.setModel(def);
}
Was it helpful?

Solution

The second list only adds one element every time and replaces it with the previous element because you created DefaultListModel inside actionPerforemed method.

To solve this issuse, define it as an instance.

private DefaultListModel modelOne = new DefaultListModel();//if you need it
private DefaultListModel modelTwo = new DefaultListModel();

//inside the constructor
//...
LCandidate.setModel(modelOne);
Lmyvotes.setModel(modelTwo);
//.....

//Inside actionPerformed

private void butCounter1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        String selec =(String) LCandidate.getSelectedValue();
      //  DefaultListModel def = new DefaultListModel();  << don't need this line 
        def.addElement(selec);

      //  Lmyvotes.setModel(def); << don't need this line too
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top