Article View: borland.public.jbuilder.java.swing
Article #9850Re: JBuilder3, JList & Sorting
From: Paul Furbacher [TeamB]
Date: Mon, 10 Jan 2000 00:00
Date: Mon, 10 Jan 2000 00:00
48 lines
2318 bytes
2318 bytes
Joe Heuler wrote:
>
> Hello,
> Using JBuilder3 and swing components I have created a ListModel that is
> displayed with JList. Objects are added to the ListModel. Each object is
> composed of two strings and one icon(one string is for display purposes and
> the other string will not be displayed in the JList). I would like to be
> able to sort the objects by either string before displaying them in the
> JList. I am able to use the Arrays.sort in java.util.Arrays but I have only
> been successful with sorting strings(not strings in objects).
>
> Does anyone know of a way to sort objects according to an element of an
> object?
Create a custom Comparator class. Override the "compare()" method.
In that method, typecast the Object parameters to your custom class.
Get the instance variable you want to base the comparison on.
Suppose you have the following custom object for each item
in your ListModel and you want to sort based on the int value.
public class MyObject {
public String name;
public int value;
public MyObject() { ... }
...
}
Now, the custom Comparator:
Comparator myComparator = new Comparator() {
public int compare(Object object1, Object object2) {
// Make sure the two objects are of the correct type.
if ( object1 instanceof MyObject && object2 instanceof MyObject ) {
Integer integer1 = new (Integer(((MyObject)object1).value));
Integer integer2 = new (Integer(((MyObject)object2).value));
reutrn integer1.compareTo(integer2);
}
else
// They aren't of the same type, so we can't make a comparison.
return 0;
}
};
Paul Furbacher (TeamB)
Technical Details
Message-ID:
<387A6DD2.69DAB413@bilbo.bio.purdue.edu>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<85325s$qhr30@bornews.borland.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 111d45,77c74362b77ebaef X-Google-Attributes: gid111d45,public From: "Paul Furbacher [TeamB]" <pf@bilbo.bio.purdue.edu> Subject: Re: JBuilder3, JList & Sorting Date: 2000/01/10 Message-ID: <387A6DD2.69DAB413@bilbo.bio.purdue.edu> X-Deja-AN: 570927186 Content-Transfer-Encoding: 7bit References: <85325s$qhr30@bornews.borland.com> Content-Type: text/plain; charset=us-ascii Organization: Reverse Alchemy, Inc. Mime-Version: 1.0 Reply-To: pf@bilbo.bio.purdue.edu Newsgroups: borland.public.jbuilder.java.swing