How to sort the jComboBox elements in java swing?

前端 未结 3 1343
孤城傲影
孤城傲影 2020-12-20 02:07

How to sort the jComboBox elements list into sorted list.

JComboBox box=new JComboBox();
box.addItem(\"abc\");
box.addItem(\"zzz\");
box.addItem         


        
3条回答
  •  無奈伤痛
    2020-12-20 02:29

    You can have a look at the SortedComboBoxModel.

    This model extends the DefaultComboBoxModel and has two additional pieces of functionality built into it:

    • upon creation of the model, the supplied data will be sorted before
    • the data is added to the model when adding new items to the model, the items will be inserted so as to maintain the sort order

    The default sort order will be the natural sort order of the items added to the model. However, you can control this by specifying a custom Comparator as a parameter of the constructor.

    Here's an example how to use it (taken from there):

    String[] items = { "one", "two", "three" };
    SortedComboBoxModel model = new SortedComboBoxModel(items);
    JComboBox comboBox = new JComboBox(model);
    comboBox.addItem("four");
    comboBox.addItem("five");
    comboBox.setSelectedItem("one");
    

    Source code

提交回复
热议问题