如何在GUI中对字符串数组进行排序? [英] How to sort a string array within a GUI?

查看:49
本文介绍了如何在GUI中对字符串数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在蓝色鹈鹕第19课项目两个订单,一个价格"上遇到麻烦.下面提供的代码是在GUI中编写的,我的问题是,当我的字符串具有多个需要打印的名称时,它仅列出升序/降序中的名字.

  String [] ss = {"Agnes",阿尔弗雷德",伯纳德"账单",以斯拉",赫尔曼",李",玛丽",托马斯"};for(int i = 0; i< ss.length; i ++){jTextArea1.setText(ss [i]);}Arrays.sort(ss,Collections.reverseOrder());for(字符串名称:ss){jTextArea2.setText(name);} 

我的GUI运行时:

解决方案

jTextArea1.setText(ss [i]); 就是这样做的,它是将文本设置"为您要使用的值例如,通常您想使用 JTextArea#append 将更多文本附加到 JTextArea StringBuilder 来构建 String 在循环中,您可以通过 setText 在单个步骤中进行应用...但是...

这可能比您想的要复杂,但是您的基本问题只是尖叫 JList .有关更多详细信息,请参见

  import java.awt.EventQueue;导入java.awt.GridBagConstraints;导入java.awt.GridBagLayout;导入java.awt.GridLayout;导入java.text.Collat​​or;导入java.util.ArrayList;导入java.util.Arrays;导入java.util.Collections;导入java.util.Comparator;导入java.util.List;导入javax.swing.AbstractListModel;导入javax.swing.DefaultListModel;导入javax.swing.JFrame;导入javax.swing.JLabel;导入javax.swing.JList;导入javax.swing.JPanel;导入javax.swing.JScrollPane;导入javax.swing.ListModel;导入javax.swing.UIManager;导入javax.swing.UnsupportedLookAndFeelException;导入javax.swing.event.ListDataEvent;导入javax.swing.event.ListDataListener;公共类SortExample {公共静态void main(String [] args){新的SortExample();}公共SortExample(){EventQueue.invokeLater(new Runnable(){@Override公共无效run(){尝试 {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());} catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex){ex.printStackTrace();}JFrame frame = new JFrame("Testing");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.add(new TestPane());frame.pack();frame.setLocationRelativeTo(null);frame.setVisible(true);}});}公共类TestPane扩展了JPanel {私人JList未排序;私有JList升序;私有JList降序;公共TestPane(){String [] ss = {"Agnes",阿尔弗雷德",伯纳德"账单",以斯拉",赫尔曼",李",玛丽",托马斯"};List< String>listOfValues = Arrays.asList(ss);Collections.shuffle(listOfValues);DefaultListModel模型=新的DefaultListModel();对于(String value:listOfValues){model.addElement(value);}setLayout(new GridBagLayout());GridBagConstraints gbc = new GridBagConstraints();gbc.gridx = 0;gbc.gridy = 0;添加(新的JLabel("Unsorted"),gbc);gbc.gridx ++;添加(新的JLabel("Ascending"),gbc);gbc.gridx ++;add(new JLabel("Descending"),gbc);未排序=新的JList(model);升序=新的JList(new SortedListModel(model,SortedListModel.SortOrder.Ascending));降序=新的JList(new SortedListModel(model,SortedListModel.SortOrder.Descending));gbc.weightx = 1;gbc.weighty = 1;gbc.fill = GridBagConstraints.BOTH;gbc.gridx = 0;gbc.gridy ++;添加(新的JScrollPane(未排序),gbc);gbc.gridx ++;添加(新的JScrollPane(升序),gbc);gbc.gridx ++;添加(新的JScrollPane(降序),gbc);}}/*** SortedListModel装饰未排序的ListModel以提供已排序的* 模型.您可以从已有模型创建SortedListModel.*例如,将SortedListModel放入JList中以提供已排序的*您的基础模型的视图.** @作者约翰·奥康纳(John O'Conner)*/公共静态类SortedListModel扩展AbstractListModel {私有ListDataHandler hndListData;私有列表< SortedListEntry>sortedModel;私有ListModel unsortedModel;专用比较器比较器;私有SortOrder sortOrder;公共枚举SortOrder {未排序上升,下降;}私人SortedListModel(){setSortOrder(SortOrder.Unsorted);setComparator(Collat​​or.getInstance());}/***使用默认文本从现有模型创建SortedListModel*用于默认语言环境的比较器.升序排列.** @param模型未排序的基础ListModel*/public SortedListModel(ListModel model){this(model,SortOrder.Ascending,null);}/***使用特定模型从现有模型创建SortedListModel*比较器和排序顺序.使用默认的文本比较器.** @param模型未排序的列表模型*应该使用的@param sortOrder*/public SortedListModel(ListModel model,SortOrder sortOrder){this(model,sortOrder,null);}/***从现有模型创建SortedListModel.对模型进行排序*使用给定的比较器指定的排序顺序.** @参数模型* @param sortOrder* @参数补偿**/public SortedListModel(ListModel model,SortOrder sortOrder,Comparator comp){这();setComparator(comp);setModel(model);setSortOrder(sortOrder);}公共无效setModel(ListModel模型){if(unsortedModel == null ||!unsortedModel.equals(model)){如果(unsortedModel!= null){fireIntervalRemoved(this,0,unsortedModel.getSize()-1);unsortedModel.removeListDataListener(getListDataHandler());}unsortedModel =模型;如果(unsortedModel!= null){unsortedModel.addListDataListener(getListDataHandler());}//获取基本模型信息int size = model.getSize();List< SortedListEntry>sortedModel = getSortedModel();sortedModel.clear();for(int x = 0; x< size; ++ x){SortedListEntry条目=新的SortedListEntry(x);int insertPoint = findInsertionPoint(entry);sortedModel.add(insertionPoint,entry);}}}受保护的ListDataHandler getListDataHandler(){如果(hndListData == null){hndListData = new ListDataHandler();}返回hndListData;}公共SortOrder getSortOrder(){返回sortOrder;}受保护的列表< SortedListEntry>getSortedModel(){如果(sortedModel == null){sortedModel = new ArrayList< SortedListEntry>(25);}返回sortedModel;}公共ListModel getModel(){返回unsortedModel;}/***从原始模型中检索排序的条目** @param index排序模型中条目的索引* @return元素是我们进入点所指向的原始模型*/公共对象getElementAt(int index)抛出IndexOutOfBoundsException {对象元素= null;如果(getModel()!= null){int modelIndex = toUnsortedModelIndex(index);element = getModel().getElementAt(modelIndex);}返回元素;}/***检索基础模型的大小** @模型的返回尺寸*/public int getSize(){int size = getSortedModel().size();返回大小;}/***将排序的模型索引转换为未排序的模型索引.** @param index排序模型中的索引* @return modelIndex未排序模型中的索引**/public int toUnsortedModelIndex(int index)引发IndexOutOfBoundsException {int modelIndex = -1;SortedListEntry条目= getSortedModel().get(index);modelIndex = entry.getIndex();返回modelIndex;}/***将排序后的模型索引数组转换为其未排序的模型*索引.对结果索引集进行排序.** @param sortedSelectedIndices中选定元素的索引*排序的模型或排序的视图* @return unsortedSelectedIndices表示未排序的选定索引* 模型*/public int [] toUnsortedModelIndices(int [] sortedSelectedIndices){int [] unsortedSelectedIndices = new int [sortedSelectedIndices.length];int x = 0;对于(int sortedIndex:sortedSelectedIndices){unsortedSelectedIndices [x ++] = toUnsortedModelIndex(sortedIndex);}//在返回之前对索引数组进行排序Arrays.sort(unsortedSelectedIndices);返回unsortedSelectedIndices;}/***将未排序的模型索引转换为已排序的模型索引.** @param unsortedIndex未排序模型中的元素索引* @return sortedIndex排序模型中的元素索引*/public int toSortedModelIndex(int unsortedIndex){int sortedIndex = -1;int x = -1;对于(SortedListEntry条目:getSortedModel()){++ x;如果(entry.getIndex()== unsortedIndex){sortedIndex = x;休息;}}返回sortedIndex;}/***将未排序的模型选择索引数组转换为*排序的模型.将模型索引从低到高排序到*复制JList的getSelectedIndices方法** @参数unsortedModelIndices* @返回排序模型中的选定索引的数组*/public int [] toSortedModelIndices(int [] unsortedModelIndices){int [] sortedModelIndices = new int [unsortedModelIndices.length];int x = 0;for(int unsortedIndex:unsortedModelIndices){sortedModelIndices [x ++] = toSortedModelIndex(unsortedIndex);}Arrays.sort(sortedModelIndices);返回sortedModelIndices;}私人无效resetModelData(){int索引= 0;对于(SortedListEntry条目:getSortedModel()){entry.setIndex(index ++);}}public void setComparator(Comparator comp){如果(比较器== null ||!comparator.equals(comp)){比较器= comp;如果(比较器== null){setSortOrder(SortOrder.Unsorted);比较器= Collat​​or.getInstance();resetModelData();} else if(getModel()!= null){Collections.sort(getSortedModel());}如果(getModel()!= null){fireContentsChanged(ListDataEvent.CONTENTS_CHANGED,0,getSortedModel().size()-1);}}}/***在运行时更改模型的排序顺序** @参数值*/public void setSortOrder(SortOrder value){if(sortOrder!= value){sortOrder = value;如果(值== SortOrder.Unsorted){resetModelData();} else if(getModel()!= null){Collections.sort(getSortedModel());}如果(getModel()!= null){fireContentsChanged(ListDataEvent.CONTENTS_CHANGED,0,getSortedModel().size()-1);}}}/***每当有新项目添加到*原始/装饰模型.**/私人无效unsortedIntervalAdded(ListDataEvent e){int begin = e.getIndex0();int end = e.getIndex1();int nElement Transactions =结束-开始+ 1;/*装饰模型中的物品已在飞行中转移.*将模型指针增加到装饰的模型中.*我们必须增加与插入相交的索引*点在装饰模型中.*/对于(SortedListEntry条目:getSortedModel()){int索引= entry.getIndex();//如果我们的模型指向模型索引> =到哪里//添加了新的模型项,我们必须增加其索引如果(索引> =开始){entry.setIndex(index + nElement Transactions);}}//现在从装饰的模型中添加新项目for(int x = begin; x< = end; ++ x){SortedListEntry newEntry =新的SortedListEntry(x);int insertPoint = findInsertionPoint(newEntry);getSortedModel().add(insertionPoint,newEntry);fireIntervalAdded(ListDataEvent.INTERVAL_ADDED,insertpoint,insertingPoint);}}/***从原件/装饰物中取出物品时更新此模型* 模型.另外,让我们的听众知道我们已删除项目.*/私人无效unsortedIntervalRemoved(ListDataEvent e){int begin = e.getIndex0();int end = e.getIndex1();int nElementsRemoved =结束-开始+ 1;/**从排序模型的结尾移至开头,进行更新*元素索引到装饰模型中或删除*必要的元素*/int sortedSize = getSortedModel().size();boolean [] bElementRemoved = new boolean [sortedSize];for(int x = sortedSize-1; x> = 0; --x){SortedListEntry条目= getSortedModel().get(x);int索引= entry.getIndex();如果(索引>结束){entry.setIndex(index-nElementsRemoved);}否则,如果(索引> =开始){getSortedModel().remove(x);bElementRemoved [x] = true;}}/**让听众知道我们已删除项目.*/for(int x = bElementRemoved.length-1; x> = 0; --x){如果(bElementRemoved [x]){fireIntervalRemoved(ListDataEvent.INTERVAL_REMOVED,x,x);}}}/***如果原始未排序的模型有变化,请重新排序模型* 模型.让任何听众知道更改.因为我不追踪*具体更改,在所有地方排序并重新显示所有项目.*/私人无效unsortedContentsChanged(ListDataEvent e){Collections.sort(getSortedModel());fireContentsChanged(ListDataEvent.CONTENTS_CHANGED,0,getSortedModel().size()-1);}/***内部帮助方法,用于在中查找新条目的插入点*排序的模型.*/私人int findInsertionPoint(SortedListEntry条目){int insertPoint = getSortedModel().size();如果(getSortOrder()!= SortOrder.Unsorted){insertingPoint = Collections.binarySearch((List)getSortedModel(),entry);如果(inserttionPoint< 0){insertPoint =-(inserttionPoint + 1);}}返回insertPoint;}公共比较器getComparator(){返回比较器;}公共类SortedListEntry实现Comparable {私人int指数;私人SortedListEntry(){}public SortedListEntry(int index){this.index =索引;}public int getIndex(){回报指数;}public void setIndex(int index){this.index =索引;}public int compareTo(Object o){int比较= 0;if(getModel()!= null&& getComparator()!= null){//检索此条目指向的元素//在原始模型中对象thisElement = getModel().getElementAt(index);SortedListEntry thatEntry =(SortedListEntry)o;//检索原始中thatEntry指向的元素//模型对象thatElement = getModel().getElementAt(thatEntry.getIndex());如果(整理者的getComparator()实例){thisElement = thisElement.toString();thatElement = thatElement.toString();}//使用提供的比较器比较基本模型的元素比较= getComparator().compare(thisElement,thatElement);//根据需要转换为降序如果(getSortOrder()== SortOrder.Descending){比较=-比较;}}返回比较;}}受保护的类ListDataHandler实现ListDataListener {公共无效intervalAdded(ListDataEvent e){unsortedIntervalAdded(e);}公共无效intervalRemoved(ListDataEvent e){unsortedIntervalRemoved(e);}公共无效contentsChanged(ListDataEvent e){unsortedContentsChanged(e);}}}} 

使用这样的代理"模型的概念可以追溯到Java 1.3,在我们有了诸如 RowSorter 之类的东西之前,您可能可以使用它,但是我已经从来没有时间去调查一下.

使用这样的代理模型是一种向组件添加新功能的好方法,而无需修改现有代码

I' having trouble with blue pelican lesson 19 project "two orders for the price of one". The code that is provided below is written within a GUI, my problem is that it only list the first name from the ascending/descending order when my string has multiple names that need to be printed.

String[] ss = {"Agnes",
               "Alfred",
               "Bernard",
               "Bill",
               "Ezra",
               "Herman",
               "Lee",
               "Mary",
               "Thomas"};
for (int i = 0; i < ss.length; i++){
    jTextArea1.setText(ss[i]);
}
Arrays.sort(ss, Collections.reverseOrder());

for (String name: ss){
    jTextArea2.setText(name);
}

My GUI when ran:

解决方案

jTextArea1.setText(ss[i]); is doing just that, it's "setting" the text to the value you are suppling, generally you either want to use JTextArea#append to append more text to the JTextArea or a StringBuilder to build a String within the loop, which you can apply in a single step through setText... however...

This is probably more complex then you were thinking, but your basic problem just screams JList. See How to Use Lists for more details.

Now, it would be very easy to simply create 3 Lists of values, using the original, unsorted list, populate the other two and use Collections.sort to sort them, but where's the fun in that.

Instead, I use a custom ListModel which can sort another ListModel in the order you want. The power of this is, the original is never changed, so it's order is preserved, but if you change either list (add/remove rows), they will both be updated

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class SortExample {

    public static void main(String[] args) {
        new SortExample();
    }

    public SortExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JList unsorted;
        private JList ascending;
        private JList descending;

        public TestPane() {
            String[] ss = {"Agnes",
                "Alfred",
                "Bernard",
                "Bill",
                "Ezra",
                "Herman",
                "Lee",
                "Mary",
                "Thomas"};
            List<String> listOfValues = Arrays.asList(ss);
            Collections.shuffle(listOfValues);
            DefaultListModel model = new DefaultListModel();
            for (String value : listOfValues) {
                model.addElement(value);
            }

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(new JLabel("Unsorted"), gbc);
            gbc.gridx++;
            add(new JLabel("Ascending"), gbc);
            gbc.gridx++;
            add(new JLabel("Descending"), gbc);

            unsorted = new JList(model);
            ascending = new JList(new SortedListModel(model, SortedListModel.SortOrder.Ascending));
            descending = new JList(new SortedListModel(model, SortedListModel.SortOrder.Descending));

            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.gridx = 0;
            gbc.gridy++;
            add(new JScrollPane(unsorted), gbc);
            gbc.gridx++;
            add(new JScrollPane(ascending), gbc);
            gbc.gridx++;
            add(new JScrollPane(descending), gbc);
        }

    }

    /**
     * SortedListModel decorates an unsorted ListModel to provide a sorted
     * model. You can create a SortedListModel from models you already have.
     * Place the SortedListModel into a JList, for example, to provide a sorted
     * view of your underlying model.
     *
     * @author John O'Conner
     */
    public static class SortedListModel extends AbstractListModel {

        private ListDataHandler hndListData;
        private List<SortedListEntry> sortedModel;
        private ListModel unsortedModel;
        private Comparator comparator;
        private SortOrder sortOrder;

        public enum SortOrder {
            Unsorted,
            Ascending,
            Descending;
        }

        private SortedListModel() {
            setSortOrder(SortOrder.Unsorted);
            setComparator(Collator.getInstance());
        }

        /**
         * Create a SortedListModel from an existing model using a default text
         * comparator for the default Locale. Sort in ascending order.
         *
         * @param model the underlying, unsorted ListModel
         */
        public SortedListModel(ListModel model) {
            this(model, SortOrder.Ascending, null);
        }

        /**
         * Create a SortedListModel from an existing model using a specific
         * comparator and sort order. Use a default text comparator.
         *
         * @param model the unsorted list model
         * @param sortOrder that should be used
         */
        public SortedListModel(ListModel model, SortOrder sortOrder) {
            this(model, sortOrder, null);
        }

        /**
         * Create a SortedListModel from an existing model. Sort the model in
         * the specified sort order using the given comparator.
         *
         * @param model
         * @param sortOrder
         * @param comp
         *
         */
        public SortedListModel(ListModel model, SortOrder sortOrder, Comparator comp) {
            this();
            setComparator(comp);
            setModel(model);
            setSortOrder(sortOrder);
        }

        public void setModel(ListModel model) {
            if (unsortedModel == null || !unsortedModel.equals(model)) {
                if (unsortedModel != null) {
                    fireIntervalRemoved(this, 0, unsortedModel.getSize() - 1);
                    unsortedModel.removeListDataListener(getListDataHandler());
                }

                unsortedModel = model;
                if (unsortedModel != null) {
                    unsortedModel.addListDataListener(getListDataHandler());
                }

                // get base model info
                int size = model.getSize();

                List<SortedListEntry> sortedModel = getSortedModel();
                sortedModel.clear();
                for (int x = 0; x < size; ++x) {
                    SortedListEntry entry = new SortedListEntry(x);
                    int insertionPoint = findInsertionPoint(entry);
                    sortedModel.add(insertionPoint, entry);
                }
            }
        }

        protected ListDataHandler getListDataHandler() {
            if (hndListData == null) {
                hndListData = new ListDataHandler();
            }
            return hndListData;
        }

        public SortOrder getSortOrder() {
            return sortOrder;
        }

        protected List<SortedListEntry> getSortedModel() {
            if (sortedModel == null) {
                sortedModel = new ArrayList<SortedListEntry>(25);
            }
            return sortedModel;
        }

        public ListModel getModel() {
            return unsortedModel;
        }

        /**
         * Retrieve the sorted entry from the original model
         *
         * @param index index of an entry in the sorted model
         * @return element in the original model to which our entry points
         */
        public Object getElementAt(int index) throws IndexOutOfBoundsException {
            Object element = null;
            if (getModel() != null) {
                int modelIndex = toUnsortedModelIndex(index);
                element = getModel().getElementAt(modelIndex);
            }
            return element;
        }

        /**
         * Retrieve the size of the underlying model
         *
         * @return size of the model
         */
        public int getSize() {
            int size = getSortedModel().size();
            return size;
        }

        /**
         * Convert sorted model index to an unsorted model index.
         *
         * @param index an index in the sorted model
         * @return modelIndex an index in the unsorted model
         *
         */
        public int toUnsortedModelIndex(int index) throws IndexOutOfBoundsException {
            int modelIndex = -1;
            SortedListEntry entry = getSortedModel().get(index);
            modelIndex = entry.getIndex();
            return modelIndex;
        }

        /**
         * Convert an array of sorted model indices to their unsorted model
         * indices. Sort the resulting set of indices.
         *
         * @param sortedSelectedIndices indices of selected elements in the
         * sorted model or sorted view
         * @return unsortedSelectedIndices selected indices in the unsorted
         * model
         */
        public int[] toUnsortedModelIndices(int[] sortedSelectedIndices) {
            int[] unsortedSelectedIndices = new int[sortedSelectedIndices.length];
            int x = 0;
            for (int sortedIndex : sortedSelectedIndices) {
                unsortedSelectedIndices[x++] = toUnsortedModelIndex(sortedIndex);
            }

            // sort the array of indices before returning
            Arrays.sort(unsortedSelectedIndices);
            return unsortedSelectedIndices;
        }

        /**
         * Convert an unsorted model index to a sorted model index.
         *
         * @param unsortedIndex an element index in the unsorted model
         * @return sortedIndex an element index in the sorted model
         */
        public int toSortedModelIndex(int unsortedIndex) {
            int sortedIndex = -1;
            int x = -1;
            for (SortedListEntry entry : getSortedModel()) {
                ++x;
                if (entry.getIndex() == unsortedIndex) {
                    sortedIndex = x;
                    break;
                }
            }
            return sortedIndex;
        }

        /**
         * Convert an array of unsorted model selection indices to indices in
         * the sorted model. Sort the model indices from low to high to
         * duplicate JList's getSelectedIndices method
         *
         * @param unsortedModelIndices
         * @return an array of selected indices in the sorted model
         */
        public int[] toSortedModelIndices(int[] unsortedModelIndices) {
            int[] sortedModelIndices = new int[unsortedModelIndices.length];
            int x = 0;
            for (int unsortedIndex : unsortedModelIndices) {
                sortedModelIndices[x++] = toSortedModelIndex(unsortedIndex);
            }

            Arrays.sort(sortedModelIndices);
            return sortedModelIndices;
        }

        private void resetModelData() {
            int index = 0;
            for (SortedListEntry entry : getSortedModel()) {
                entry.setIndex(index++);
            }
        }

        public void setComparator(Comparator comp) {
            if (comparator == null || !comparator.equals(comp)) {
                comparator = comp;
                if (comparator == null) {
                    setSortOrder(SortOrder.Unsorted);
                    comparator = Collator.getInstance();

                    resetModelData();
                } else if (getModel() != null) {
                    Collections.sort(getSortedModel());
                }

                if (getModel() != null) {
                    fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, getSortedModel().size() - 1);
                }
            }
        }

        /**
         * Change the sort order of the model at runtime
         *
         * @param value
         */
        public void setSortOrder(SortOrder value) {
            if (sortOrder != value) {
                sortOrder = value;
                if (value == SortOrder.Unsorted) {
                    resetModelData();
                } else if (getModel() != null) {
                    Collections.sort(getSortedModel());
                }

                if (getModel() != null) {
                    fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, getSortedModel().size() - 1);
                }
            }
        }

        /**
         * Update the sorted model whenever new items are added to the
         * original/decorated model.
         *
         */
        private void unsortedIntervalAdded(ListDataEvent e) {
            int begin = e.getIndex0();
            int end = e.getIndex1();
            int nElementsAdded = end - begin + 1;

            /* Items in the decorated model have shifted in flight.
                 * Increment our model pointers into the decorated model.
                 * We must increment indices that intersect with the insertion
                 * point in the decorated model.
             */
            for (SortedListEntry entry : getSortedModel()) {
                int index = entry.getIndex();
                // if our model points to a model index >= to where
                // new model entries are added, we must bump up their index
                if (index >= begin) {
                    entry.setIndex(index + nElementsAdded);
                }
            }

            // now add the new items from the decorated model
            for (int x = begin; x <= end; ++x) {
                SortedListEntry newEntry = new SortedListEntry(x);
                int insertionPoint = findInsertionPoint(newEntry);

                getSortedModel().add(insertionPoint, newEntry);

                fireIntervalAdded(ListDataEvent.INTERVAL_ADDED, insertionPoint, insertionPoint);
            }
        }

        /**
         * Update this model when items are removed from the original/decorated
         * model. Also, let our listeners know that we've removed items.
         */
        private void unsortedIntervalRemoved(ListDataEvent e) {
            int begin = e.getIndex0();
            int end = e.getIndex1();
            int nElementsRemoved = end - begin + 1;

            /*
                 * Move from end to beginning of our sorted model, updating
                 * element indices into the decorated model or removing
                 * elements as necessary
             */
            int sortedSize = getSortedModel().size();
            boolean[] bElementRemoved = new boolean[sortedSize];

            for (int x = sortedSize - 1; x >= 0; --x) {
                SortedListEntry entry = getSortedModel().get(x);
                int index = entry.getIndex();
                if (index > end) {
                    entry.setIndex(index - nElementsRemoved);
                } else if (index >= begin) {
                    getSortedModel().remove(x);
                    bElementRemoved[x] = true;
                }
            }
            /*
                 * Let listeners know that we've removed items.
             */
            for (int x = bElementRemoved.length - 1; x >= 0; --x) {
                if (bElementRemoved[x]) {
                    fireIntervalRemoved(ListDataEvent.INTERVAL_REMOVED, x, x);
                }
            }
        }

        /**
         * Resort the sorted model if there are changes in the original unsorted
         * model. Let any listeners know about changes. Since I don't track
         * specific changes, sort everywhere and redisplay all items.
         */
        private void unsortedContentsChanged(ListDataEvent e) {
            Collections.sort(getSortedModel());
            fireContentsChanged(ListDataEvent.CONTENTS_CHANGED, 0, getSortedModel().size() - 1);
        }

        /**
         * Internal helper method to find the insertion point for a new entry in
         * the sorted model.
         */
        private int findInsertionPoint(SortedListEntry entry) {
            int insertionPoint = getSortedModel().size();
            if (getSortOrder() != SortOrder.Unsorted) {
                insertionPoint = Collections.binarySearch((List) getSortedModel(), entry);
                if (insertionPoint < 0) {
                    insertionPoint = -(insertionPoint + 1);
                }
            }
            return insertionPoint;
        }

        public Comparator getComparator() {
            return comparator;
        }

        public class SortedListEntry implements Comparable {

            private int index;

            private SortedListEntry() {
            }

            public SortedListEntry(int index) {
                this.index = index;
            }

            public int getIndex() {
                return index;
            }

            public void setIndex(int index) {
                this.index = index;
            }

            public int compareTo(Object o) {

                int comparison = 0;
                if (getModel() != null && getComparator() != null) {
                    // retrieve the element that this entry points to
                    // in the original model
                    Object thisElement = getModel().getElementAt(index);
                    SortedListEntry thatEntry = (SortedListEntry) o;
                    // retrieve the element that thatEntry points to in the original
                    // model
                    Object thatElement = getModel().getElementAt(thatEntry.getIndex());
                    if (getComparator() instanceof Collator) {
                        thisElement = thisElement.toString();
                        thatElement = thatElement.toString();
                    }
                    // compare the base model's elements using the provided comparator
                    comparison = getComparator().compare(thisElement, thatElement);
                    // convert to descending order as necessary
                    if (getSortOrder() == SortOrder.Descending) {
                        comparison = -comparison;
                    }
                }

                return comparison;
            }
        }

        protected class ListDataHandler implements ListDataListener {

            public void intervalAdded(ListDataEvent e) {
                unsortedIntervalAdded(e);
            }

            public void intervalRemoved(ListDataEvent e) {
                unsortedIntervalRemoved(e);
            }

            public void contentsChanged(ListDataEvent e) {
                unsortedContentsChanged(e);
            }
        }
    }

}

The concept of using a "proxy" model like this goes WAY back to Java 1.3, before we had things like RowSorter, which you might be able to use for this instead, but I've never had the time to go back an investigate it.

Using proxy models like this is a great way of adding new functionality to components, without the need to modify the existing code

这篇关于如何在GUI中对字符串数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆