如何在java swing中对jComboBox元素进行排序? [英] How to sort the jComboBox elements in java swing?
问题描述
如何将 jComboBox
元素列表排序为排序列表。
How to sort the jComboBox
elements list into sorted list.
JComboBox box=new JComboBox();
box.addItem("abc");
box.addItem("zzz");
box.addItem("ccc");
add(box);
我使用了很多jComboBox组件,但它不起作用。
如何按升序对此列表进行排序?
i used many jComboBox Components but it's not working. How to sort this list into ascending order?
推荐答案
您可以查看 SortedComboBoxModel
。
You can have a look at the SortedComboBoxModel
.
此模型扩展了DefaultComboBoxModel并且内置了两个额外的
功能:
This model extends the DefaultComboBoxModel and has two additional pieces of functionality built into it:
- 创建模型后,提供的数据将在之前排序
- 在向模型添加新项目时将数据添加到模型中,将插入
项目以维护排序顺序
默认排序顺序是添加到模型中的项目
的自然排序顺序。但是,您可以通过将
自定义Comparator指定为构造函数的参数来控制此。
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<String> model = new SortedComboBoxModel<String>(items);
JComboBox<String> comboBox = new JComboBox<String>(model);
comboBox.addItem("four");
comboBox.addItem("five");
comboBox.setSelectedItem("one");
这篇关于如何在java swing中对jComboBox元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!