Reputation: 15
I have a JList that is filled with an Array. I just want to print the value when the user selects something in the list and presses a button. I know it's something to do with getSelectedValues. When I searched online I got solutions to JLists filled with addItems but not when filled with an Array.
This is the code for the button at the moment:
public void actionPerformed(ActionEvent evt) {
Object[] selected = FilmList.getSelectedValues();
String[] selectedItems = new String[selected.length];
System.out.println(selectedItems);
}
The name of my JList is FilmList and the name of my array is films. Thanks guys.
Upvotes: 0
Views: 1353
Reputation: 13066
EDIT
you should use
Object[] selected = FilmList.getSelectedValues(); System.out.println(java.util.Arrays.toString(selected));
OR If you want to store it in array of String you can do like this:
String[] selectedItems = new String[selected.length];
for (int i = 0 ; i < selectedItems.length ; i++)
{
selectedItems[i] = (String)selected[i];
}
And then you can print the same as:
System.out.println(Arrays.toString(selectedItems));
You can also print the values using for loop as:
for (int i =0; i < selectedItems.length ; i++)
System.out.println(selectedItems[i]));
Upvotes: 0
Reputation: 1509
public void actionPerformed(ActionEvent evt) {
Object[] selectedFilms = FilmList.getSelectedValues();
for(int i = 0; i < selectedFilms.length; i++)
System.out.print(selectedFilms[i].toString + ", ");
System.out.println();
}
May be you can do it shorter? Something like this?
Upvotes: 1