简体   繁体   中英

add an element to Jlist

I have two JList s.

List A has these elements:

  • 1
  • two
  • 78
  • item4

List B that is for now empty.

My frame has these two list and a button Verify . Once I click on the button, the selected item of List A gets verified whether it is an integer. If so, the selected item has to be transfered to List B and removed from List A.

What I did so far is when clicking on the button, the item get copied but once I selected another item the previous one get replaced with the new item which I don't want.

How can transfer (append) the item to the other list and remove it from the first one, this way I have got finally the list with all the items without being replaced by the new items.

Use a DefaultListModel .

DefaultListModel dlmA = new DefaultListModel(); // For list A
dlmA.addElement(1);
dlmA.addElement("two");
dlmA.addElement(78);
dlmA.addElement("item4");

listA.setModel(dlmA);

Now, the same for your list B.

DefaultListModel dlmB = new DefaultListModel(); // For list B
listB.setModel(dlmB);

If you want to add items to your second list, just add them to the DefaultListModel dlmB . This means you have to keep a reference to dlmB in your working class, this way you can add elements to it inside the ActionListener of your button.

public void actionPerformed(ActionEvent evt)
{
    // Perform your checks. If you want to add it to list B, use:
    dlmB.addElement(yourNewElem);
}

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