import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * ChooseStringDialog *
* This class models a modal dialog box that allows a user to choose * one or more items (all strings) from a list displayed to him/her * * @version 0.1 alpha * * @author * This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated with * its operation, modification and maintenance. */ public class ChooseStringDialog extends JDialog { private static ChooseStringDialog dialog; private static String[] values = null; private JList list; /** * Does intialization for a new dialog box * * @param com the parent component * @param choices array of strings user will choose from * @param title title of dialog box * @param labelText subtitle over the list of choices * @param selectionalModel - only one choice or multiple allowed */ public static void initialize(Component comp, String[] choices, String title, String labelText, int selectionModel) { Frame frame = JOptionPane.getFrameForComponent(comp); dialog = new ChooseStringDialog(frame, choices, title, labelText, selectionModel); } /** * Shows the dialog box and returns user's choice(s) * * @param comp component over which the dialog will appear * @param initialValue a choice to highlight when dialog first appears * @return an array with the choice(s) the user made */ public static String[] showDialog(Component comp, String initialValue) { if (dialog != null) { dialog.setValue(initialValue); dialog.setLocationRelativeTo(comp); dialog.setVisible(true); } else { System.err.println("ChooseStringDialog requires you to call initialize " + "before calling showDialog."); } return values; } private void setValue(String newValue) { if (values == null) values = new String[1]; values[0] = newValue; list.setSelectedValue(values[0], true); } private ChooseStringDialog(Frame frame, Object[] data, String title, String labelText, int selectionModel) { super(frame, title, true); //buttons JButton cancelButton = new JButton("Cancel"); final JButton setButton = new JButton("Set"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ChooseStringDialog.dialog.setVisible(false); } }); setButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selectModel = list.getSelectionMode(); if (selectModel == ListSelectionModel.SINGLE_SELECTION) { values = new String[1]; ChooseStringDialog.values[0] = (String)list.getSelectedValue(); } else { Object[] listArr = list.getSelectedValues(); if (listArr != null) { int numSelections = listArr.length; values = new String[numSelections]; for (int i=0; i