Article View: borland.public.jbuilder.java.swing
Article #12973Re: Sorting the items in a JList
From: Alexander Anguiano
Date: Wed, 14 Oct 1998 00:00
Date: Wed, 14 Oct 1998 00:00
118 lines
3127 bytes
3127 bytes
>Hi,
>
>does someone knows how to sort the items in a JList?
>
>alex
>
Hello
Here is a sorted list model that I created. It is not fully complete
because I only needed a sorted list from a to z.
use it like this:
SortedListModel definedKeys = new SortedListModel();
definedKeys.addSorted(keyList);
jlist1.setModel(definedKeys); // give it a list model
------------------------------------------------
//Title: Utils
//Version:
//Copyright: Copyright (c) 1997
//Author: Alexander Anguiano
//Company: Matrix Computing
//Description:
package utils;
import com.sun.java.swing.DefaultListModel;
import java.util.*;
public class SortedListModel extends DefaultListModel {
private boolean ignoreDuplicates;
public SortedListModel() {
ignoreDuplicates = true;
}
/*
public SortedListModel(SortFunction) {
}
*/
public void setIgnoreDuplicates(boolean ignoreDuplicates) {
this.ignoreDuplicates = ignoreDuplicates;
}
public boolean isIgnoreDuplicates() {
return ignoreDuplicates;
}
// add just keeps the thing sorted
public void addSorted(Object Item1) {
int nTop;
int nBottom;
int nMiddle;
int nLocation;
int CompareResults = 0;
int nSize;
nSize = size();
if (nSize < 1)
nLocation = 0;
else {
nTop = nSize - 1;
nBottom = 0;
nMiddle = (nTop - nBottom) / 2;
while (true) {
Object Item2 = elementAt(nMiddle);
CompareResults = Item1.toString().compareTo(Item2.toString());
if (CompareResults < 0) {
if (nTop == nMiddle)
nTop = nMiddle - 1;
else nTop = nMiddle;
}
else if (CompareResults > 0) {
if (nBottom == nMiddle)
nBottom = nMiddle + 1;
else nBottom = nMiddle;
}
else {
if (ignoreDuplicates)
return;
// if (!duplicates)
// return -1;
nTop = nMiddle;
nBottom = nMiddle;
}
if ( ((nBottom == nTop) && (nTop == nMiddle)) || (nTop < nBottom) )
break;
nMiddle = (nTop - nBottom) / 2 + nBottom;
} // while
if (CompareResults > 0)
nLocation = nMiddle + 1;
else nLocation = nMiddle;
} // if
insertElementAt(Item1,nLocation);
}
public void addSorted(Vector list) {
for (int i= 0; i < list.size(); i++) {
addSorted(list.elementAt(i));
}
}
}
Technical Details
Message-ID:
<702gjb$k0n15@forums.borland.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<36247087.B27288E@cimag.de>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 111d45,5e76ce43feffb479 X-Google-Attributes: gid111d45,public From: "Alexander Anguiano" <AlexAnguiano@worldnet.att.net> Subject: Re: Sorting the items in a JList Date: 1998/10/14 Message-ID: <702gjb$k0n15@forums.borland.com> X-Deja-AN: 401015107 References: <36247087.B27288E@cimag.de> X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3 Organization: Another Netscape Collabra Server User Newsgroups: borland.public.jbuilder.java.swing