我们如何使用 Java 排序 JComboBox 的项目?
JComboBox 是JComponent 类的子类,它是文本字段和下拉列表的组合,用户可以在其中选择一个值。JComboBox 当用户对组合框进行操作时,可以生成ActionListener、ChangeListener和ItemListener 接口。默认情况下,JComboBox 不支持对项目进行排序,我们可以通过扩展DefaultComboBoxModel 类来定制代码。
示例
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class JComboBoxSorterTest extends JFrame {
private JComboBox comboBox;
private JTextField textField;
public JComboBoxSorterTest() {
setTitle("JComboBoxSorter Test");
setLayout(new FlowLayout());
textField = new JTextField(10);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
comboBox.addItem(textField.getText());
textField.setText("");
comboBox.showPopup();
}
});
String[] items = {"raja", "archana", "vineet", "krishna", "adithya"};
SortedComboBoxModel model = new SortedComboBoxModel(items);
comboBox = new JComboBox(model);
comboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
Box box1 = Box.createHorizontalBox();
box1.add(new JLabel("Enter a name and hit enter "));
box1.add(textField);
Box box2 = Box.createHorizontalBox();
box2.add(comboBox);
add(box1);
add(box2);
setSize(375, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
// Customize the code for sorting of items in the JComboBox
private class SortedComboBoxModel extends DefaultComboBoxModel {
public SortedComboBoxModel() {
super();
}
public SortedComboBoxModel(Object[] items) {
Arrays.sort(items);
int size = items.length;
for (int i = 0; i < size; i++) {
super.addElement(items[i]);
}
setSelectedItem(items[0]);
}
public SortedComboBoxModel(Vector items) {
Collections.sort(items);
int size = items.size();
for (int i = 0; i < size; i++) {
super.addElement(items.elementAt(i));
}
setSelectedItem(items.elementAt(0));
}
public void addElement(Object element) {
insertElementAt(element, 0);
}
public void insertElementAt(Object element, int index) {
int size = getSize();
for (index = 0; index < size; index++) {
Comparable c = (Comparable) getElementAt(index);
if (c.compareTo(element) > 0) {
break;
}
}
super.insertElementAt(element, index);
}
}
public static void main(String[] args) {
new JComboBoxSorterTest();
}
}输出
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP