001    /* $Id: JDoubleList.java 12 2007-07-27 09:48:53Z ringler $
002     * This class is part of the de.mospace.swing library.
003     * Copyright (C) 2005-2006 Moritz Ringler
004     *
005     * This program is free software; you can redistribute it and/or
006     * modify it under the terms of the GNU General Public License
007     * as published by the Free Software Foundation; either version 2
008     * of the License, or (at your option) any later version.
009     *
010     * This program is distributed in the hope that it will be useful,
011     * but WITHOUT ANY WARRANTY; without even the implied warranty of
012     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013     * GNU General Public License for more details.
014     *
015     * You should have received a copy of the GNU General Public License
016     * along with this program; if not, write to the Free Software
017     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
018     */
019    package de.mospace.swing;
020    
021    import java.awt.Component;
022    import java.awt.Dimension;
023    import java.awt.GridBagConstraints;
024    import java.awt.GridBagLayout;
025    import java.awt.GridLayout;
026    import java.awt.Insets;
027    import java.awt.ScrollPane;
028    import java.awt.event.ActionEvent;
029    import java.awt.event.ActionListener;
030    import java.awt.event.FocusAdapter;
031    import java.awt.event.FocusEvent;
032    import java.util.Arrays;
033    import javax.swing.DefaultListModel;
034    import javax.swing.JButton;
035    import javax.swing.JComponent;
036    import javax.swing.JList;
037    import javax.swing.JPanel;
038    import javax.swing.JScrollPane;
039    import javax.swing.ListModel;
040    import de.mospace.swing.icon.ArrowIcon;
041    import de.mospace.swing.icon.DoubleArrowIcon;
042    
043    /**
044     * A two-column list where items can be moved from one side to the other.
045     * The order of the items can also be adjusted.
046     *
047     * @version $Revision: 12 $ ($Date: 2007-07-27 11:48:53 +0200 (Fr, 27 Jul 2007) $)
048     * @author Moritz Ringler
049     */
050    public class JDoubleList extends JPanel{
051    
052        /** Minimum requirements on a model for one of the JLists. **/
053        public static interface SingleListModel extends ListModel{
054            public Object remove(int index);
055            public void add(int index, Object element);
056        }
057    
058        public static class DefaultSingleListModel extends DefaultListModel implements SingleListModel{
059            public DefaultSingleListModel(){
060                super();
061            }
062        }
063    
064        public static final int MOVE_RIGHT = 0;
065        public static final int MOVE_LEFT  = 1;
066        public static final int MOVE_UP    = 2;
067        public static final int MOVE_DOWN  = 3;
068        public static final int MOVE_START = 4;
069        public static final int MOVE_END   = 5;
070        public static final int LEFT = 0;
071        public static final int CENTER = 1;
072        public static final int RIGHT = 2;
073        private final JList listL, listR;
074        JList activeList = null;
075        private ScrollPane left, right;
076        private JPanel buttonPane;
077        private JButton[] buttons;
078        private JComponent[] compo;
079        private boolean symmetric = true;
080        private boolean rightOrderFixed = false;
081        private boolean leftOrderFixed = false;
082    
083        private class ScrollPane extends JScrollPane{
084            public ScrollPane(Component c){
085                super(c);
086            }
087    
088            /** This method assures that both scrollpanes always have
089                the same size if this DoubleList is symmetric. **/
090            public Dimension getPreferredSize(){
091                Dimension d = getPreferredIndividualSize();
092                if(symmetric){
093                    Dimension d1 = (this == left)
094                        ? right.getPreferredIndividualSize()
095                        : left.getPreferredIndividualSize();
096                    d.height = Math.max(d.height, d1.height);
097                    d.width = Math.max(d.width, d1.width);
098                }
099                return d;
100            }
101    
102            /** This method returns the preferred size of one of the
103             scrollpanes. When the list in a scrollpane is empty
104             Swing dumbly assings a width of 256 px. We use the dimension
105             of the other list and if both are empty a width and height of
106             40 px. **/
107            public Dimension getPreferredIndividualSize(){
108                boolean isLeft = (this == left);
109                boolean myListEmpty = isEmpty(isLeft ? listL : listR);
110                boolean bothEmpty = isEmpty(listL) && isEmpty(listR);
111    
112                return (myListEmpty)
113                    ? ((bothEmpty)
114                            ? new Dimension(40,40)
115                            : (isLeft? right : left).getPreferredIndividualSize())
116                    : super.getPreferredSize();
117            }
118    
119            private boolean isEmpty(JList list){
120                return (list.getModel().getSize() == 0);
121            }
122        }
123    
124        public void setSymmetric(boolean symm){
125            symmetric = symm;
126        }
127    
128        public boolean isSymmetric(){
129            return symmetric;
130        }
131    
132        /** An element of a {@link JDoubleList}. It consists of an object and
133        * the information whether this object can be moved from one side of a
134        * double list to the other.
135        **/
136        public static class ListElement{
137            private final Object obj;
138            private boolean mov;
139    
140            /** Constructs a new DoubleList element with the
141             * given movable property. **/
142            public ListElement(Object o, boolean movable){
143                obj = o;
144                mov = movable;
145            }
146    
147            /** Returns whether this element can be moved from one side of a
148            * double list to the other.
149            * @see #setMovable(boolean)
150            **/
151            public boolean getMovable(){
152                return mov;
153            }
154    
155            /** Returns the object of this ListElement. **/
156            public Object getObject(){
157                return obj;
158            }
159    
160            /** Changes the movable property of this double list element.
161            * @see #getMovable()
162            **/
163            public void setMovable(boolean b){
164                mov = b;
165            }
166        }
167    
168        /** Constructs a new double list. The SingleListModels in this double
169            list will be instances of javax.swing.DefaultListModel. **/
170        public JDoubleList(){
171            listL = new JList(new DefaultSingleListModel());
172            listR = new JList(new DefaultSingleListModel());
173            init();
174        }
175    
176        /** Constructs a new double list from the given single list models. **/
177        public JDoubleList(SingleListModel left, SingleListModel right){
178            listL = new JList(left);
179            listR = new JList(right);
180            init();
181        }
182    
183        /** Constructs a new double List from the given single list models. **/
184        public JDoubleList(SingleListModel left, SingleListModel right,
185                boolean leftOrderFixed, boolean rightOrderFixed){
186            this.leftOrderFixed = leftOrderFixed;
187            this.rightOrderFixed = rightOrderFixed;
188            listL = new JList(left);
189            listR = new JList(right);
190            init();
191        }
192    
193        /** Constructs a new double List from the given single lists. If the list
194        * models do not implement SingleListModel an IllegalArgumentException is thrown.
195        * @throws IllegalArgumentException if at least one of the list models is not an instance of SingleListModel
196        **/
197        public JDoubleList(JList left, JList right,
198                boolean leftOrderFixed, boolean rightOrderFixed){
199            if(!
200                (
201                    (left.getModel() instanceof SingleListModel) &&
202                    (right.getModel() instanceof SingleListModel)
203                )
204               ){
205                   throw new IllegalArgumentException("List models must be instances of SingleListModel.");
206            }
207            this.leftOrderFixed = leftOrderFixed;
208            this.rightOrderFixed = rightOrderFixed;
209            listL = left;
210            listR = right;
211            init();
212        }
213    
214        private void init(){
215            FocusAdapter fa = new FocusAdapter(){
216                public void focusGained(FocusEvent e){
217                    activeList = (JList) e.getSource();
218                }
219            };
220            ActionListener al = new ActionListener(){
221                public void actionPerformed(ActionEvent e){
222                    JButton src = (JButton) e.getSource();
223                    if (src == buttons[MOVE_RIGHT]){
224                        moveRight();
225                    } else if (src == buttons[MOVE_LEFT]){
226                        moveLeft();
227                    } else if (src == buttons[MOVE_UP]){
228                        moveUp();
229                    } else if (src == buttons[MOVE_DOWN]){
230                        moveDown();
231                    } else if (src == buttons[MOVE_START]){
232                        moveStart();
233                    } else if (src == buttons[MOVE_END]){
234                        moveEnd();
235                    }
236                }
237            };
238            listL.addFocusListener(fa);
239            listR.addFocusListener(fa);
240            left = new ScrollPane(listL);
241            right = new ScrollPane(listR);
242            buttonPane = new JPanel();
243    
244            JButton moveLeft  = new JButton(
245                    new ArrowIcon(ArrowIcon.DIRECTION_LEFT));
246            JButton moveRight = new JButton(
247                    new ArrowIcon(ArrowIcon.DIRECTION_RIGHT));
248            JButton moveUp    = new JButton(
249                    new ArrowIcon(ArrowIcon.DIRECTION_UP));
250            JButton moveDown  = new JButton(
251                    new ArrowIcon(ArrowIcon.DIRECTION_DOWN));
252            JButton moveStart = new JButton(
253                    new DoubleArrowIcon(DoubleArrowIcon.DIRECTION_UP));
254            JButton moveEnd   = new JButton(
255                    new DoubleArrowIcon(DoubleArrowIcon.DIRECTION_DOWN));
256            buttons = new JButton[]{
257                moveRight,
258                moveLeft,
259                moveUp,
260                moveDown,
261                moveStart,
262                moveEnd
263            };//do not change the order of the entries!! @see #getButton(int)
264            Insets buttonInsets = new Insets(3,3,3,3);
265    
266            for (int i=0; i<buttons.length; i++){
267                buttons[i].setMargin(buttonInsets);
268                buttons[i].addActionListener(al);
269            }
270            buttonPane.setLayout(new GridLayout(3,2,2,2));
271            buttonPane.add(moveLeft);
272            buttonPane.add(moveRight);
273            buttonPane.add(moveUp);
274            buttonPane.add(moveDown);
275            buttonPane.add(moveStart);
276            buttonPane.add(moveEnd);
277            setLayout(new GridBagLayout());
278            GridBagConstraints gbc = new GridBagConstraints();
279            gbc.gridy = 0;
280            gbc.gridwidth = 1;
281            gbc.gridheight = 1;
282            gbc.weighty = 1.0;
283    
284            gbc.gridx = 0;
285            gbc.weightx = 0.5;
286            gbc.fill = GridBagConstraints.BOTH;
287            add(left, gbc);
288    
289            gbc.gridx = 2;
290            add(right, gbc);
291    
292            gbc.gridx = 1;
293            gbc.weightx = 0.0;
294            gbc.insets = new Insets(0,10,0,10);
295            gbc.fill = GridBagConstraints.NONE;
296            add(buttonPane, gbc);
297    
298            compo = new JComponent[]{
299                left,
300                buttonPane,
301                right
302            };//do not change the order of the entries!! @see #setComponentSize(int)
303        }
304    
305        public Component getPart(int part){
306            Component result;
307            switch(part){
308                case LEFT:
309                    result = left;
310                    break;
311                case CENTER:
312                    result = buttonPane;
313                    break;
314                case RIGHT:
315                    result = right;
316                    break;
317                default:
318                    throw new IllegalArgumentException("Part must be one of LEFT, CENTER, RIGHT.");
319            }
320            return result;
321        }
322    
323        /** Moves the selected elements in the src list into the dst list.
324        * New items are added after the last selected item or after the last item
325        * in the dst list.
326        * @param src source list
327        * @param dst target list
328        **/
329        private void move(JList src, JList dst){
330            if (src.isSelectionEmpty()){
331                return;
332            }
333            int pos;
334            SingleListModel msrc = (SingleListModel) src.getModel();
335            SingleListModel mdst = (SingleListModel) dst.getModel();
336            if (dst.isSelectionEmpty()){
337                pos = mdst.getSize();
338            } else {
339                pos = dst.getMaxSelectionIndex();
340            }
341            int[] srcIndices = src.getSelectedIndices();
342            Arrays.sort(srcIndices);
343            for (int i = srcIndices.length -1; i >= 0; i--){
344                Object element = msrc.getElementAt(srcIndices[i]);
345                if(
346                    (element instanceof ListElement)
347                        ? ((ListElement) element).getMovable()
348                        : true
349                  ){
350                    mdst.add(pos,msrc.remove(srcIndices[i]));
351                }
352            }
353        }
354    
355        /** Moves the selected elements from the list on the right
356        * into the list on the left.
357        * New items are added after the last selected item or
358        * - if there is no selection - after the last item
359        * in the target list.
360        **/
361        public final void moveLeft(){
362            move(listR, listL);
363        }
364    
365        /** Moves the selected elements from the list on the left
366        * into the list on the right.
367        * New items are added after the last selected item or
368        * - if there is no selection - after the last item
369        * in the target list.
370        **/
371        public final void moveRight(){
372            move(listL, listR);
373        }
374    
375        private void moveUp(){
376            if (
377                    activeList == null ||
378                    activeList.isSelectionEmpty() ||
379                    activeList.getMinSelectionIndex() == 0 ||
380                    (activeList == listL && leftOrderFixed) ||
381                    (activeList == listR && rightOrderFixed)
382                ){
383                return;
384            }
385            int[] indices = activeList.getSelectedIndices();
386            SingleListModel alm = (SingleListModel) activeList.getModel();
387            Arrays.sort(indices);
388            Object buff = null;
389            for (int j=0; j<indices.length;j++){
390                buff = alm.remove(indices[j]);
391                alm.add(indices[j]-1, buff);
392                indices[j]--;
393            }
394            activeList.setSelectedIndices(indices);
395        }
396    
397        private void moveDown(){
398            SingleListModel alm = (SingleListModel) activeList.getModel();
399            if (
400                    activeList == null ||
401                    activeList.isSelectionEmpty() ||
402                    activeList.getMaxSelectionIndex() == alm.getSize()-1 ||
403                    (activeList == listL && leftOrderFixed) ||
404                    (activeList == listR && rightOrderFixed)
405               ){
406                return;
407            }
408            int[] indices = activeList.getSelectedIndices();
409            Arrays.sort(indices);
410            Object buff = null;
411            for (int j=indices.length-1; j>=0;j--){
412                buff = alm.remove(indices[j]);
413                alm.add(indices[j]+1, buff);
414                indices[j]++;
415            }
416            activeList.setSelectedIndices(indices);
417        }
418    
419        private void moveStart(){
420            if (activeList == null || activeList.isSelectionEmpty()||
421                    (activeList == listL && leftOrderFixed) ||
422                    (activeList == listR && rightOrderFixed)){
423                return;
424            }
425            SingleListModel alm = (SingleListModel) activeList.getModel();
426            int[] indices = activeList.getSelectedIndices();
427            Arrays.sort(indices);
428            Object buff = null;
429            for (int j=0; j<indices.length;j++){
430                buff = alm.remove(indices[j]);
431                alm.add(j, buff);
432                indices[j] = j;
433            }
434            activeList.setSelectedIndices(indices);
435        }
436    
437        private void moveEnd(){
438            if (activeList == null || activeList.isSelectionEmpty() ||
439                    (activeList == listL && leftOrderFixed) ||
440                    (activeList == listR && rightOrderFixed)){
441                return;
442            }
443            SingleListModel alm = (SingleListModel) activeList.getModel();
444            int[] indices = activeList.getSelectedIndices();
445            Arrays.sort(indices);
446            Object buff = null;
447            int target  = alm.getSize();
448            for (int j=indices.length-1; j>=0;j--){
449                buff = alm.remove(indices[j]);
450                alm.add(--target, buff);
451                indices[j] = target;
452            }
453            activeList.setSelectedIndices(indices);
454        }
455    
456        /** Returns the JList displayed on the left. **/
457        public JList getLeftList(){
458            return listL;
459        }
460    
461        /** Returns the JList displayed on the right. **/
462        public JList getRightList(){
463            return listR;
464        }
465    
466        /** Returns one of the buttons that manipulate the double list.
467        * @param movexxx one of MOVE_RIGHT, MOVE_LEFT, MOVE_UP, MOVE_DOWN, MOVE_START, MOVE_END
468        **/
469        public JButton getButton(int movexxx){
470            if (movexxx < 0 || movexxx >= buttons.length){
471                throw new IllegalArgumentException("Argument must be one of one of"+
472                                                   "MOVE_RIGHT, MOVE_LEFT, MOVE_UP"+
473                                                   ", MOVE_DOWN, MOVE_START, "+
474                                                   "MOVE_END");
475            }
476            return buttons[movexxx];
477        }
478    
479        /** Adjusts the size of one of the three double list components.
480         * @param comp one of LEFT (list), RIGHT (list), and CENTER (buttons)
481         * @param d the new preferred size for the respective component
482         **/
483         public void setComponentSize(int comp, Dimension d){
484             compo[comp].setPreferredSize(d);
485             updateUI();
486         }
487    }