[英]Update JList with Custom Arraylist
I have attempted to convert my program to a GUI.我试图将我的程序转换为 GUI。 I have 2 custom Arraylists of type subject (b & m) I need to setListData to the custom object type b when the B button is pressed and m when the M button is pressed.我有 2 个主题类型 (b & m) 的自定义 Arraylists 我需要在按下 B 按钮时将 ListData 设置为自定义对象类型 b,在按下 M 按钮时将 m 设置为自定义对象类型。 So far my List looks like到目前为止,我的列表看起来像
LabelCoreSubs.setText("Core Subjects:");
ListCoreSub.setModel(new AbstractListModel<String>() {
String[] strings = {};
public int getSize() {
return strings.length;
}
public String getElementAt(int i) {
return strings[i];
}
});
jScrollPane1.setViewportView(ListCoreSub);
I can call this custom arraylist through ArrayList b = B.getCores();我可以通过 ArrayList b = B.getCores(); 调用这个自定义数组列表; how would i get this arraylist to display in my Jlist.我如何让这个数组列表显示在我的 Jlist 中。 I have also attempted to change the JList type to Subject but with no luck.我也尝试将 JList 类型更改为 Subject 但没有成功。
How do I update my JList to display each list on a button click event.如何更新我的 JList 以在按钮单击事件上显示每个列表。
The setListData()
method of JList
only works for an Array or a Vector, so you can't use it with an ArrayList
. JList
的setListData()
方法仅适用于 Array 或 Vector,因此您不能将它与ArrayList
一起使用。
So you can:这样你就可以:
DefaultListModel
.创建一个DefaultListModel
。addAll(...)
method of the DefaultListModel
to copy the items of the ArrayList
into the model.使用DefaultListModel
的addAll(...)
方法将ArrayList
的项复制到模型中。setModel(...)
method of the JList
.使用JList
的setModel(...)
方法。 A better approach is to not create two ArrayLists to hold the initial data.更好的方法是不创建两个 ArrayList 来保存初始数据。 Instead just create a DefaultListModel
and add the data directly to the model.而只是创建一个DefaultListModel
并将数据直接添加到模型中。 This way the data is only in one place.这样,数据只在一个地方。 And to change the data displayed in the JList
you just use the setModel(...)
method.要更改JList
显示的数据,您只需使用setModel(...)
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.