Show input dialog in item selection mode with specified title, message and initial selection. - Java Swing

Java examples for Swing:JDialog

Description

Show input dialog in item selection mode with specified title, message and initial selection.

Demo Code

/*/*w  w  w  .  ja v  a 2  s.c  o  m*/
 * Copyright (c) 2011, 2020, Frank Jiang and/or its affiliates. All rights
 * reserved. SwingUtils.java is built in 2012-11-2.
 */
//package com.java2s;
import java.awt.Component;

import javax.swing.JOptionPane;

public class Main {
    /**
     * Show input dialog in item selection mode with specified title, message
     * and initial selection.
     * 
     * @param parent
     *            the parent component of the input dialog, set {@code null} if
     *            not has one
     * @param title
     *            the title of the dialog
     * @param message
     *            the message to display
     * @param initial
     *            an array of <code>Object</code>s that
     *            gives the possible selections
     * @param selections
     *            the value used to initialize the input
     *            field
     * @return the index of the selected item, or <code>-1</code> if user
     *         canceled input.
     */
    public static int selectIndexDialog(Component parent, String title,
            String message, Object initial, Object[] selections) {
        Object obj = JOptionPane.showInputDialog(parent, message, title,
                JOptionPane.INFORMATION_MESSAGE, null, selections, initial);
        if (obj != null)
            for (int i = 0; i < selections.length; i++)
                if (obj.equals(selections[i]))
                    return i;
        return -1;
    }
}

Related Tutorials