Skip to Content
author's profile photo Former Member
Former Member

Sorting a DefaultListModel

Hi all,

I have a HTMLB dropdownListBox which is filled with a DefaultListModel showing a country selection. The listbox is sorted by the countrycode (AD,AE,AF,AG,AL,AM ...)

, but I want it to be sorted by the country text (Andorra,

United Arab Emirates,Afghanistan,Antigua/Barbuda,Albania ...).

How can this be done?

Kind regards,

Francisco

This is the code which fills the model:

for (int i = 0; i < countryTableNumRows; i++) {
countryTable.setRow(i);
countryModel.addItem(countryTable.getString("COUNTRY"), countryTable.getString("COUNTRYTXT"));
}

Add a comment
10|10000 characters needed characters exceeded

Related questions

1 Answer

  • Best Answer
    Posted on Oct 05, 2004 at 10:02 AM

    Hi Francisco,

    the keys and texts within the DefaultListModel are backed up by ArrayLists. So the order of the entries is determined by the order in which the keys/texts are added to the model.

    You say "listbox is sorted by the countrycode" - the sort order in your example comes from the order the entries are found within the table.

    Just as a proposal: Create an object CountryModelEntry (consists of key and text), implement Comparable and define the order by the order of the text. Then create an ArrayList with all CountryModelEntries, sort this and create the ListModel in the order you get back by your sorted list.

    Hope it helps

    Detlev

    Add a comment
    10|10000 characters needed characters exceeded

    • Former Member Detlev Beutner

      Wow, thanks a lot for your fast and very helpful answer!

      Hope your head is not shaking anymore 😉

      Kind regards

      Francisco

      Edit:

      Just found a small typo in the last code:

      for (int i = 0; i < countryModelEntries.size(); i++) {
      					CountryModelEntry orderedEntry = (CountryModelEntry) countryModelEntries.get(i);
      					countryModel.addItem(orderedEntry.getCountryKey(), orderedEntry.getCountryText());
      				}

      Message was edited by: Francisco Villar

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.