CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: List order

  1. #1
    Join Date
    Mar 2000
    Posts
    123

    List order

    Any way to keep list box elemens (JList) in alpha order, even after and addElement?


  2. #2
    Join Date
    Sep 2000
    Location
    Melbourne --> Australia
    Posts
    68

    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.






  3. #3
    Join Date
    Mar 2000
    Posts
    123

    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
  •  





Click Here to Expand Forum to Full Width

Featured