簡體   English   中英

如何在java swing中對jComboBox元素進行排序?

[英]How to sort the jComboBox elements in java swing?

如何將jComboBox元素列表排序為排序列表。

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

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

您可以查看SortedComboBoxModel

此模型擴展了DefaultComboBoxModel,並在其中內置了兩個額外的功能:

  • 在創建模型時,提供的數據將在之前進行排序
  • 在向模型添加新項目時將數據添加到模型中,將插入項目以維護排序順序

默認排序順序是添加到模型中的項目的自然排序順序。 但是,您可以通過將自定義Comparator指定為構造函數的參數來控制此操作。

這是一個如何使用它的例子(取自那里 ):

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

源代碼

您可以覆蓋addItem的默認行為以滿足您的需要。

可運行的例子

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

雖然源鏈接仍然有效,但Alexis C.的SortedComboBoxModel鏈接似乎不再起作用了。

盡管如此,我為實現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);
    }
}

這可以這樣使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM