【问题标题】:How to sort the jComboBox elements in java swing?java - 如何对java swing中的jComboBox元素进行排序?
【发布时间】:2013-06-08 07:38:29
【问题描述】:

如何将jComboBox 元素列表排序到排序列表中。

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

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

【问题讨论】:

  • 只需按正确的顺序添加它们。您可以先将它们添加到List 并使用Collections#sort 以避免手动排序
  • 需要在运行时添加元素..
  • 在这种情况下见MutableComboBoxModel#insertElementAt

标签: java swing jcombobox


【解决方案1】:

你可以看看SortedComboBoxModel

这个模型扩展了 DefaultComboBoxModel 并且有两个额外的 内置的功能:

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

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

这是一个如何使用它的例子(取自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

【讨论】:

    【解决方案2】:

    您可以覆盖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);
                }
            });
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      不过,我为实现 Comparable 的类创建了一个 SortedComboBoxModel(基于 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);
          }
      }
      

      可以这样使用:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-25
        • 2020-06-24
        • 2015-05-30
        • 2021-03-24
        • 1970-01-01
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        相关资源
        最近更新 更多