daileyps
September 14th, 2000, 04:43 PM
Any way to keep list box elemens (JList) in alpha order, even after and addElement?
|
Click to See Complete Forum and Search --> : List order daileyps September 14th, 2000, 04:43 PM Any way to keep list box elemens (JList) in alpha order, even after and addElement? Phill September 15th, 2000, 03:00 AM 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. daileyps September 15th, 2000, 01:27 PM Thanks, I'll give this a try and see if it works. codeguru.com
Copyright Internet.com Inc., All Rights Reserved. |