|
-
September 14th, 2000, 04:43 PM
#1
List order
Any way to keep list box elemens (JList) in alpha order, even after and addElement?
-
September 15th, 2000, 03:00 AM
#2
Re: List order
Hi
You can try a TreeSet (from the new Collections)
This will put them in sorted order.
You can have an add method which adds the Strings
to the TreeSet and another method which retrieves them from the TreeSet and add them to the
JList so it will be in Alphabetical.
-----------------
You will need to import the java.util package
and have and anonymous inner class in your constructor
somthing like this :
TreeSet tset; // outside constructor
//then inside constructor
tset = new TreeSet(new Comparator(){
public int compare(Object one, Object two){
String a = ((String)one).toUpperCase(); //calls to UpperCase() so that it wont matter if the letters are Uppercase or not they will still be in Alphabetical order.
String b = ((String)two).toUpperCase();
return(a.compareTo(b));
}
public boolean equals(Object obj){
return false;
}
});
Then you can have an add method somthing like
this:
void add(String s){
tset.add(s);
}
So when you want to add a String you can just
call the add(String s) method. You can even
call this method from a loop, this would be
good if you have a String array that you want
to add.
for(int i = 0; i < stray.length; i++)
add(yourArray[i]);
Then to retrieve the String, you need an Iterator.
void printStrings(){
Iterator it = tset.iterator();
while(it.hasNext())
System.out.println(it.next());
}
Instead of printing the Strings out, just add them
to your JList
I hope this is clear enough.
There is a good tutorial on the Collections
at the Sun website.
Phill.
-
September 15th, 2000, 01:27 PM
#3
Re: List order
Thanks, I'll give this a try and see if it works.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|