JAME
JAME

Reputation: 29

Swings: storing the selected values from List into an array.

I made a List in java as under:

 String names[] = {"[email protected]", "[email protected]","[email protected]","[email protected]"};
 JList places = new JList(names) ;

Then in order to access the selected values I wrote in valueChanged method :

String[] emailID= places.getSelectedValuesList().toString[];

which is coming out to be incorrect ... Kindly help how should I rewrite this line so as the selected values get stored in array.

Upvotes: 0

Views: 1345

Answers (2)

Roger
Roger

Reputation: 1225

For Storing Selected Items in String Array you can try this

  Object[] values = places.getSelectedValues();
    String[] strings = new String[values.length];
    for(int i = 0; i < values.length; i++) {
      if(values[i] instanceof String) {
        strings[i] = ((String) values[i]);
      }
    }

Upvotes: 1

Loki
Loki

Reputation: 4130

If you want to have all selected Items as an Array you can do something like this:

public static void main(String[] args){

    String names[] = {"[email protected]", "[email protected]","[email protected]","[email protected]"};
    JList<String> places = new JList<String>(names) ;

    places.setSelectedIndices(new int[]{0,1,2});

    String[] emailIDs = places.getSelectedValuesList().toArray(new String[]{});

    for(String s : emailIDs){
        System.out.println(s);
    }
}

Note:

I added <String> to the List, because I assume you always want to have Strings as values. That way you can get the List .toArray() method with a generic output. Else you'd need to get an Object[] (Object Array) and cast the values.

Upvotes: 1

Related Questions