我正在尝试从数据库中获取名称和ID,并将它们添加到组合框中。我已将此checkcombobox添加到我的项目中;
借助此代码; https://stackoverflow.com/a/17097767
ResultSet resultSet= "here getting the result set with query having a ORDER BY clause
while (resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
System.out.println(name);
options.add(new Option<Integer>(name, id));
}
system.out.println给出按名称排序的输出,但checkcombobox中的项目未排序。如何添加在组合框中排序的项目?
答案 0 :(得分:0)
Set
构造函数,请使用CheckComboBox(Map<Object, Boolean> mapObjSelected)
构造函数。TreeMap
。 Set
构造函数默认创建LinkedHashMap
,但不保留顺序。Option
的代码中正确实施compareTo
method。您可能需要添加一个额外的字段来告诉Option
他们应该在哪个顺序。答案 1 :(得分:0)
这是一种对计算箱中的项目进行排序的方法。
首先使用Option
或实施Comparator
界面,然后
Comparable
进行排序
然后从排序列表中添加项目。
Collections.sort(options);
comboBox.removeAllItems();
for (Option s : options) {
comboBox.addItem(s);
}
完整示例
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SortCombo {
JComboBox comboBox;
JButton sortButton;
List<Option> options;
public SortCombo() {
options = createOptions();
comboBox = new JComboBox(options.toArray());
sortButton = new JButton("Sort");
sortButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Collections.sort(options);
comboBox.removeAllItems();
for (Option s : options) {
comboBox.addItem(s);
}
}
});
JFrame frame = new JFrame("Sort ComboBox");
frame.add(comboBox, BorderLayout.CENTER);
frame.add(sortButton, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public List<Option> createOptions() {
List<Option> list = new ArrayList<>();
list.add(new Option("John", 1));
list.add(new Option("Sean", 2));
list.add(new Option("Jake", 3));
list.add(new Option("Mike", 4));
list.add(new Option("Abby", 5));
list.add(new Option("Paul", 6));
list.add(new Option("Daniel", 7));
list.add(new Option("Chris", 8));
return list;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SortCombo();
}
});
}
}
class Option implements Comparable<Option> {
private String name;
private int id;
public Option(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public int compareTo(Option option) {
return this.name.compareTo(option.name);
}
@Override
public String toString() {
return name + " {" + id + "}";
}
}