Class Listmaker

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JPanel
                  extended by Listmaker
All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible, javax.swing.event.ListSelectionListener

public class Listmaker
extends javax.swing.JPanel
implements java.awt.event.ActionListener, javax.swing.event.ListSelectionListener

A GUI component that allows the user to build a list from another list, by adding, deleting, and reordering items.

The component shows two lists: list1, on the left, contains the elements the user may choose from, while list2, on the right, represents the user-made list.
The user can then transfer elements from list1 to list2, delete elements from list2, or change the order of elements in list2. Multiple elements may be selected at any time.
An optional Sort button on the top of each list allows the user to sort a list.

The Listmaker can be used as a JPanel component or a standalone modal dialog.
The simplest way to use it as a JPanel is shown in the following example:

 Listmaker lm = new Listmaker(
                                  new JLabel("Make a list of tea flavours"),
                                  new String[] {"Earl Grey",
                                                "English Breakfast",
                                                "Darjeeling",
                                                "Java Green",
                                                "Lapsang Souchong"}
                                  );
 lm.addPropertyChangeListener(new PropertyChangeListener() {
    public void propertyChange(PropertyChangeEvent evt) {
             if (Listmaker.PROP_OKCANCEL_BUTTON.equals(evt.getPropertyName())) {
                    Object[] result = lm.getUserChoice();
       }
    }
 });
 
The result array then holds the result of the user's choice. It is recommended to add a PropertyChangeListener and call getUserChoice() only after a PropertyChangeEvent has been received; this in order to to ensure that the user has clicked either on Ok or Cancel and hence has validated his choice.

And to use Listmaker as a dialog:

 Object[] result = Listmaker.showListmakerDialog(
                                                     frame, 
                                                     new JLabel("Make a list of tea flavours"),
                                                     "It's always tea time!",
                                                     new String[] {"Earl Grey",
                                                                   "English Breakfast",
                                                                   "Darjeeling",
                                                                   "Java Green",
                                                                   "Lapsang Souchong"}
                                                     );
 
where frame is the parent frame of the dialog.

Author:
Daniele Raffo
See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel
 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
private  javax.swing.JButton buttonCancel
           
private  javax.swing.JButton buttonDelete
           
private  javax.swing.JButton buttonMovedown
           
private  javax.swing.JButton buttonMoveup
           
private  javax.swing.JButton buttonOK
           
private  javax.swing.JButton buttonSort1
           
private  javax.swing.JButton buttonSort2
           
private  javax.swing.JButton buttonTransfer
           
private  javax.swing.JButton buttonTransferall
           
private  java.awt.Dialog dialog
           
private  boolean duplicatesAllowed
           
private  javax.swing.JList list1
           
private  javax.swing.JList list2
           
private  javax.swing.DefaultListModel model1
           
private  javax.swing.DefaultListModel model2
           
static java.lang.String PROP_CANCEL_BUTTON
          The PropertyChangeEvent fired when the Cancel button is clicked.
static java.lang.String PROP_OK_BUTTON
          The PropertyChangeEvent fired when the OK button is clicked.
static java.lang.String PROP_OKCANCEL_BUTTON
          The PropertyChangeEvent fired when either the OK or the Cancel button is clicked.
private static long serialVersionUID
           
static int SORT_BOTH
          Specifies that the GUI should add sort buttons to both list1 and list2.
static int SORT_LIST1
          Specifies that the GUI should add a sort button to list1 only.
static int SORT_LIST2
          Specifies that the GUI should add a sort button to list2 only.
static int SORT_NONE
          Specifies that the GUI should add no sort button to lists.
private  java.lang.Object[] userChoice
           
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
  Listmaker(javax.swing.JLabel label, java.lang.Object[] items1, java.lang.Object[] items2, boolean duplicatesAllowed, int sortType)
          Builds a Listmaker component panel.
private Listmaker(javax.swing.JLabel label, java.lang.Object[] items1, java.lang.Object[] items2, boolean duplicatesAllowed, int sortType, java.awt.Dialog dialog)
          Private constructor.
 
Method Summary
 void actionPerformed(java.awt.event.ActionEvent e)
           
private  void add(javax.swing.JList list, javax.swing.DefaultListModel model, java.lang.Object[] array)
          Adds the specified array to list.
private  void checkEnablingButtons()
          Checks which button must be enabled/disabled, depending on the internal Listmaker's state.
static java.lang.Object[] concatenate(java.lang.Object[] array1, java.lang.Object[] array2)
          Concatenates two arrays.
static java.lang.String getLongestString(java.lang.Object[] array)
          Given an array of Objects, finds the Object having the longest String representation.
 java.lang.Object[] getUserChoice()
          Gets the user's choice.
static java.lang.Object[] showListmakerDialog(javax.swing.JFrame frame, javax.swing.JLabel label, java.lang.String title, java.lang.Object[] items1, java.lang.Object[] items2, boolean duplicatesAllowed, int sortType)
          Brings up a Listmaker dialog.
private  void sort(javax.swing.JList list, javax.swing.DefaultListModel model)
          Sorts the content of a JList.
private  void swap(javax.swing.DefaultListModel model, int indexA, int indexB)
          Swaps the place of two elements in the list that uses the specified model.
 void valueChanged(javax.swing.event.ListSelectionEvent e)
           
 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

serialVersionUID

private static final long serialVersionUID
See Also:
Constant Field Values

PROP_OK_BUTTON

public static final java.lang.String PROP_OK_BUTTON
The PropertyChangeEvent fired when the OK button is clicked.

See Also:
Constant Field Values

PROP_CANCEL_BUTTON

public static final java.lang.String PROP_CANCEL_BUTTON
The PropertyChangeEvent fired when the Cancel button is clicked.

See Also:
Constant Field Values

PROP_OKCANCEL_BUTTON

public static final java.lang.String PROP_OKCANCEL_BUTTON
The PropertyChangeEvent fired when either the OK or the Cancel button is clicked.

See Also:
Constant Field Values

SORT_NONE

public static final int SORT_NONE
Specifies that the GUI should add no sort button to lists.

See Also:
Constant Field Values

SORT_LIST1

public static final int SORT_LIST1
Specifies that the GUI should add a sort button to list1 only.

See Also:
Constant Field Values

SORT_LIST2

public static final int SORT_LIST2
Specifies that the GUI should add a sort button to list2 only.

See Also:
Constant Field Values

SORT_BOTH

public static final int SORT_BOTH
Specifies that the GUI should add sort buttons to both list1 and list2.

See Also:
Constant Field Values

list1

private javax.swing.JList list1

list2

private javax.swing.JList list2

model1

private javax.swing.DefaultListModel model1

model2

private javax.swing.DefaultListModel model2

buttonTransfer

private javax.swing.JButton buttonTransfer

buttonTransferall

private javax.swing.JButton buttonTransferall

buttonDelete

private javax.swing.JButton buttonDelete

buttonMoveup

private javax.swing.JButton buttonMoveup

buttonMovedown

private javax.swing.JButton buttonMovedown

buttonOK

private javax.swing.JButton buttonOK

buttonCancel

private javax.swing.JButton buttonCancel

buttonSort1

private javax.swing.JButton buttonSort1

buttonSort2

private javax.swing.JButton buttonSort2

duplicatesAllowed

private boolean duplicatesAllowed

dialog

private java.awt.Dialog dialog

userChoice

private java.lang.Object[] userChoice
Constructor Detail

Listmaker

private Listmaker(javax.swing.JLabel label,
                  java.lang.Object[] items1,
                  java.lang.Object[] items2,
                  boolean duplicatesAllowed,
                  int sortType,
                  java.awt.Dialog dialog)
Private constructor. To build a Listmaker panel component, call Listmaker#ListSelector(JLabel, Object[], Object[], boolean, int) instead.

Parameters:
label - a label that is shown on the top of the dialog. May also be null, in which case an empty label is used
items1 - the list of items to put on list1
items2 - the list of items to put on list2. May also be null, which specifies an empty list
duplicatesAllowed - if true, list2 is allowed to contain more than one instance of the same item (i.e. duplicates) from list1
sortType - specifies whether the GUI should include a sort button on top of lists: SORT_NONE, SORT_LIST1, SORT_LIST2, or SORT_BOTH
dialog - if the Listmaker is used as a dialog, the modal dialog purporting to this Listmaker. If the Listmaker is shown as a JPanel component of an user-created frame, this value is null

Listmaker

public Listmaker(javax.swing.JLabel label,
                 java.lang.Object[] items1,
                 java.lang.Object[] items2,
                 boolean duplicatesAllowed,
                 int sortType)
Builds a Listmaker component panel.

Parameters:
label - a label that is shown on the top of the dialog. May also be null, in which case an empty label is used
items1 - the list of items to put on list1
items2 - the list of items to put on list2. May also be null, which specifies an empty list
duplicatesAllowed - if true, list2 is allowed to contain more than one instance of the same item (i.e. duplicates) from list1
sortType - specifies whether the GUI should include a sort button on top of lists: SORT_NONE, SORT_LIST1, SORT_LIST2, or SORT_BOTH
Method Detail

showListmakerDialog

public static java.lang.Object[] showListmakerDialog(javax.swing.JFrame frame,
                                                     javax.swing.JLabel label,
                                                     java.lang.String title,
                                                     java.lang.Object[] items1,
                                                     java.lang.Object[] items2,
                                                     boolean duplicatesAllowed,
                                                     int sortType)
Brings up a Listmaker dialog.

Parameters:
frame - the parent JFrame of the dialog. If null, a new JFrame is created, and disposed of after the user's choice
label - a label that is shown on the top of the dialog. May also be null, in which case an empty label is used
title - the title of the dialog
items1 - the list of items to put on list1
items2 - the list of items to put on list2. May also be null, which specifies an empty list
duplicatesAllowed - if true, list2 is allowed to contain more than one instance of the same item (i.e. duplicates) from list1
sortType - specifies whether the GUI should include a sort button on top of lists: SORT_NONE, SORT_LIST1, SORT_LIST2, or SORT_BOTH
Returns:
the array of items chosen by the user in list2 (may also be empty) if user clicked Ok, or null if user clicked Cancel

actionPerformed

public final void actionPerformed(java.awt.event.ActionEvent e)
Specified by:
actionPerformed in interface java.awt.event.ActionListener

valueChanged

public final void valueChanged(javax.swing.event.ListSelectionEvent e)
Specified by:
valueChanged in interface javax.swing.event.ListSelectionListener

getUserChoice

public final java.lang.Object[] getUserChoice()
Gets the user's choice. This is equal to: The user's choice value is updated after every click of the user on Ok or Cancel. It is therefore recommended to call this method only after having listened to a PropertyChangeEvent PROP_OK_BUTTON, PROP_CANCEL_BUTTON, or PROP_OKCANCEL_BUTTON.

Returns:
the content of list2, or null
See Also:
PROP_OK_BUTTON, PROP_CANCEL_BUTTON, PROP_OKCANCEL_BUTTON

swap

private final void swap(javax.swing.DefaultListModel model,
                        int indexA,
                        int indexB)
Swaps the place of two elements in the list that uses the specified model.

Parameters:
model - the model used by the list whose elements are going to be swapped
indexA - the index of the element to put at indexB
indexB - the index of the element to put at indexA

sort

private final void sort(javax.swing.JList list,
                        javax.swing.DefaultListModel model)
Sorts the content of a JList. Note that, if duplicatesAllowed is false, calling this method will destroy all duplicates (if any) in the sorted list.

Parameters:
list - the list to be sorted
model - the model used by list

add

private final void add(javax.swing.JList list,
                       javax.swing.DefaultListModel model,
                       java.lang.Object[] array)
Adds the specified array to list. The items are added after the (last) selected element in list, or at the end if nothing is selected; the latter includes the case in which list is empty.

Parameters:
list - the list to which add array
model - the model of list
array - the array of items to add to list

checkEnablingButtons

private final void checkEnablingButtons()
Checks which button must be enabled/disabled, depending on the internal Listmaker's state.


getLongestString

public static final java.lang.String getLongestString(java.lang.Object[] array)
Given an array of Objects, finds the Object having the longest String representation.

Parameters:
array - the array to examine
Returns:
the longest String representation of any Object contained in the array

concatenate

public static final java.lang.Object[] concatenate(java.lang.Object[] array1,
                                                   java.lang.Object[] array2)
Concatenates two arrays.

Parameters:
array1 - a non-null array
array2 - an array (may be null)
Returns:
the array obtained by concatenating array1 with array2