Adding a list item to a JList from another JList

The following code works for me

made_list.setListData(original_list.getSelectedValues());

here made_list is one JList, and original_list is another JList. If I run with this code, the selected value from original_list replaces the previous value in made_list. I do not want it. I want to add instead. How to do it?

+3
source share
1 answer
1) Get the model for made_list
2) Get the selected items from orig_list
3) Make a new object[] that is the size of 1) + 2)
4) populate 3) with the items from 1) + 2)
5) set the make_list model with the object[] from 4)

Implementation:

ListModel made_model = made_list.getModel(); // 1

Object[] orig_sel = orig_list.getSelectedItems(); // 2

Object[] new_made_model = new Object[made_model.size() + orig_sel.length]; // 3

// this block is 4
int i = 0;
for(;i < made_model.size(); i++) 
    new_made_model[i] = made_model.getElementAt(i);
for(; i < new_made_model.length; i++) 
    new_made_model[i] = orig_sel[i - made_model.size());

made_model.setListData(new_made_model); // 5
+3
source

Source: https://habr.com/ru/post/1794288/


All Articles