java 如何在java swing中对jComboBox元素进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17061314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:51:45  来源:igfitidea点击:

How to sort the jComboBox elements in java swing?

javaswingjcombobox

提问by karthi

How to sort the jComboBoxelements list into sorted list.

如何将jComboBox元素列表排序为排序列表。

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

i used many jComboBox Components but it's not working. How to sort this list into ascending order?

我使用了许多 jComboBox 组件,但它不起作用。如何将此列表按升序排序?

回答by Alexis C.

You can have a look at the SortedComboBoxModel.

你可以看看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.

该模型扩展了 DefaultComboBoxModel 并在其中内置了两个附加功能:

  • 创建模型后,提供的数据将在之前排序
  • 向模型添加新项目时将数据添加到模型,项目将被插入以保持排序顺序

默认排序顺序将是添加到模型中的项目的自然排序顺序。但是,您可以通过将自定义 Comparator 指定为构造函数的参数来控制这一点。

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");

Source code

源代码

回答by Bnrdo

You can override the default behavior of addItemto suit your needs.

您可以覆盖 的默认行为addItem以满足您的需要。

Runnable Example

可运行示例

public class SortedCombobox {

    @SuppressWarnings("serial")
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Overriden JCombobox");
                frame.getContentPane().setLayout(new BorderLayout());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JComboBox box = new JComboBox(){
                    @Override public void addItem(Object obj){
                        int count = getItemCount();
                        String toAdd = (String) obj;

                        List<String> items = new ArrayList<String>();
                        for(int i = 0; i < count; i++){
                            items.add((String)getItemAt(i));
                        }

                        if(items.size() == 0){
                            super.addItem(toAdd);
                            return;
                        }else{
                            if(toAdd.compareTo(items.get(0)) <= 0){
                                insertItemAt(toAdd, 0);
                            }else{
                                int lastIndexOfHigherNum = 0;
                                for(int i = 0; i < count; i++){
                                    if(toAdd.compareTo(items.get(i)) > 0){
                                        lastIndexOfHigherNum = i;
                                    }
                                }
                                insertItemAt(toAdd, lastIndexOfHigherNum+1);
                            }
                        }
                    }
                };

                box.addItem("zzz");
                box.addItem("hh");
                box.addItem("aa");
                box.addItem("yy");
                box.addItem("uu");
                box.addItem("bb");
                box.addItem("rr");
                box.addItem("aa");
                box.setSelectedIndex(0);

                frame.getContentPane().add(box);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

回答by Aceman1987

The SortedComboBoxModel link from Alexis C. does not appear to work anymore, although the source link still works.

尽管源链接仍然有效,但来自 Alexis C. 的 SortedComboBoxModel 链接似乎不再有效。

Nonetheless, I created a SortedComboBoxModel for classes that implement Comparable (based on this example).

尽管如此,我还是为实现 Comparable 的类创建了一个 SortedComboBoxModel(基于此示例)。

public class SortedComboBoxModel<E extends Comparable<? super E>> extends DefaultComboBoxModel<E> {

    public SortedComboBoxModel() {
        super();
    }

    public SortedComboBoxModel(E[] 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<E> items) {
        Collections.sort(items);
        int size = items.size();
        for (int i = 0; i < size; i++) {
            super.addElement(items.elementAt(i));
        }
        setSelectedItem(items.elementAt(0));
    }

    @Override
    public void addElement(E element) {
        insertElementAt(element, 0);
    }

    @Override
    public void insertElementAt(E 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);
    }
}

This can be used like so:

这可以像这样使用:

public static void main(String[] args) {
    javax.swing.JComboBox<String> sortedComboBox = new javax.swing.JComboBox<>();
    String[] testArray = new String[]{"DDD", "AAA", "CCC", "BBB"};
    sortedComboBox.setModel(new SortedComboBoxModel<>(testArray));

    //print out the sorted contents
    for (int i = 0; i < sortedComboBox.getItemCount(); i++) {
        System.out.println(i + ": " + sortedComboBox.getItemAt(i));
    }
}