问题描述
我有
JList<myElement> list
其中包含
listmodel listModel = new DefaultListModel<myElement>()
as它的数据模型。我动态地将我的元素添加到listModel。我想将每个元素按字母顺序放入listModel(所以我的listModel总是排序!),关于它们的toString()方法返回的内容。
我尝试了下面的代码,但它删除了所有元素并按字母顺序添加它们。
as its data model. I add my element to listModel dynamically. I want to put each element in alphabetical order when is added to listModel (so my listModel is always sorted!)regarding to what their toString() method is return.
I have try following code, but it remove all the element and add them in alphabetical order.
public void sortList(){
myElement temp;
myElement[] ob = new myElement[listModel.getSize()];
for(int i = 0 ; i <listModel.getSize(); i++ )
ob[i] = listModel.getElementAt(i);
int n=ob.length;
for(int i=0;i<n;i++)
for(int j=0;j<n-i-1;j++)
{
if(ob[j].toString().compareTo(ob[j+1].toString())>0) // used to sort strings
{
temp=ob[j];
ob[j]=ob[j+1];
ob[j+1]=temp;
}
}
listModel.removeAllElements();
for(int i=0;i<n;i++)
listModel.addElement((myElement) ob[i]);
System.out.println("sort!");
}
我也用jLabel代表他们!
also I represent them with jLabel!
推荐答案
Collection list = Collections.list(listModel.elements()); // get a collection of the elements in the model
Collections.sort(list); // sort
listModel.clear(); // remove all elements
for(Object o:list){ listModel.addElement(o); } // add elements
之类的东西。
您还可以提取数组
并通过 []。br />
JList应该自动更新视图。
玩得开心!
something like that.
You can also extract an Array
and sort it via a Comparator[^].
JList should update view automatically.
Have fun!
这篇关于如何在将新项添加到其DefaultListModel时对元素的JList进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!