简体   繁体   中英

JList retrieving data from a jlist

How can I get the 3 individual strings from the JList? If I use model.elementAt I get the strings, but they are not separated from each other.

  • How is the data stored in the JList?
  • Can i perhaps get the data separated from each other by using an array?
  • Is the data stored in a array?
while(resultaat.next()){
    model.addElement(resultaat.getString(1) + "  "
        + resultaat.getString(2) + "  "
        + resultaat.getString(3));
}

I use that line of code to add a bunch of strings to a JList model. The strings are from a mysql database.

Create some kind of container object that can represent the values you want, that is capable of displaying the values in the format that you want...

public class ListObject {
    private String[] values;
    public ListObject(String... values) {
        this.values = values;
    }

    public int size() {
        return values == null ? 0 : values.length;
    }

    public String get(int index) {
        return values == null ? null : values[index];
    }

    public String toString() {
        StringBuilder sb = new StringBuilder(64);
        if (values != null) {
            for (String value : values) {
                if (sb.length() > 0) {
                    sb.append(" ");
                }
                sb.append(value);
            }
        }
        return sb.toString();
    }
}

Add the wrapper object to the model...

while(resultaat.next()){
    model.addElement(new ListObject(resultaat.getString(1),
        resultaat.getString(2),
        resultaat.getString(3)));
}

And when you need to, retrieve the values...

String value = model.getElementAt(index).get(0);

For example

How is the data stored in the JList? - they are stored actualy in Model of jList so you must call jList.getModel().getElementAt() insteed of call only jList().getElement()

Can i perhaps get the data separated from each other by using an array? yes look at my example

Is the data stored in a array? No they are in model of jList

try this code to get your jlist model into array of object

// create array with Model size
Object[] arrayOfElements = new Object[yourjList.getModel().getSize()];

// easy loop for adding elements from jList to array
 for(int i = 0; i< yourjList.getModel().getSize(); i++){

                            arrayOfElements[i] = yourjList.getModel().getElementAt(i);
            }

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