How to sort the jComboBox elements in java swing?

前端 未结 3 1331
孤城傲影
孤城傲影 2020-12-20 02:07

How to sort the jComboBox elements list into sorted list.

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


        
相关标签:
3条回答
  • 2020-12-20 02:21

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

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

    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));
        }
    }
    
    0 讨论(0)
  • 2020-12-20 02:29

    You can have a look at the 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.

    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

    0 讨论(0)
  • 2020-12-20 02:35

    You can override the default behavior of addItem to suit your needs.

    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);
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题