Fabian Montossi Fabian Montossi - 1 year ago 62
Java Question

I got an error when i try to getSelectedValue() from a JList to another JList

i i'm trying as it says the title, to get the selected item on a JList and add it to the second JList when i press a Button:

btnAdd.addActionListener(new ActionListener (){

public void actionPerformed(ActionEvent arg0) {



So, when i write that, in AddElement it asks me to cast list_1 to an Object, looking like this, becasue of this error:

enter image description here

Then after adding the Cast as it asks me to, i got the same error like if i didn't added anything.

So my question is, how do i add something from one JList to another JList when pressing a button? And if i will have the same problems for removing the last item added, or the selectedItem, please let me know how to prevent it.

The full code:

JList list = new JList();
list.setModel(new AbstractListModel(){
String[] values = new String[] {"Aceite de oliva", "Aceitunas negras", "Aceitunas verdes", "Albahaca", "Alcachofa", "Anchoas", "Berenjena", "Cebolla", "Cereza", "Champiniones", "Durazno", "Harina de garbanzo", "Huevo", "Jam\u00F3n", "Jam\u00F3n serrano", "Ma\u00EDz", "Morr\u00F3n rojo", "Morr\u00F3n verde", "Or\u00E9gano", "Palmitos", "Pi\u00F1a", "Queso cheddar", "Queso crema", "Queso gorgonzola ", "Queso muzzarella", "Queso parmesano", "Salame", "Tomates", "Tomillo"};
public int getSize() {
return values.length;
public Object getElementAt(int index) {
return values[index];


JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(373, 28, 184, 257);

JList list_1 = new JList();
list_1.setModel(new AbstractListModel() {
String[] values2 = new String[] {"", "", "", "", "", "", "", "", ""};
public int getSize() {
return values2.length;
public Object getElementAt(int index) {
return values2[index];


enter image description here

I have visited a lot of websites with different kind of Lists / Models, and as i really don't get how to use JLists i couldn't figure out what i'm doing wrong.

Answer Source

You need to add the Object to the DefaultListModel of the JList.

You can use the addElement(...) method of the DefaultListModel.

i really don't get how to use JLists

Read the section from the Swing tutorial on How to Use Lists for JList basics. The "Hire" button from the ListDemo example will show you how to do this. It uses the insertElementAt(...) method but the concept is the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download