简体   繁体   中英

JComboBox listing a String from an ArrayList of objects

I have an ArrayList that is getting objects that contain user information from a file

once the load is complete, I need the name property from each object to be loaded into a JComboBox , so that the user can choose the username to continue.

this conversion from an ArrayList<object> user --> String[] strName is where I'm having trouble

any help would be greately appreciated!

String[] values = list.toArray(new String[list.size()]);

您可以轻松地遍历ArrayList并使用DefaultComboBoxModel's addElement方法

There's a good tutorial on how to work with combo boxes here .

ArrayList<User> users;
int nUsers = users.size();
String[] userNames = new String[nUsers];
for (int i=0;i <nUsers; ++i) {
    User user = users.get(i);
    userNames[i] = user.getName();
}
JComboBox userList = new JComboBox(userNames);

If the list is ArrayList<Object> then you'll need to either:

// call toString on the object...
userNames[i] = String.valueOf(user);
// or cast it if you know the type
User user = (User)users.get(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