JOptionPane.showInputDialog with a JList?

Is there any quick and easy way to use the JOptionPane.showInputDialog with a JList? the default is a drop down menu. Thanks!

Is there any quick and easy way to use the
JOptionPane.showInputDialog with a JList? the default
is a drop down menu. Thanks!I have found a way to this. You need to write your own JOptionPane
class MyJOptionPane
    public static Object showListInputDialog(Component parentComponent, Object message, String title, Object[] selecttionValues)
        Object defaultOptionPaneUI = UIManager.get("OptionPaneUI");
        UIManager.put("OptionPaneUI", "MyBasicOptionPaneUI");
        Object object = JOptionPane.showInputDialog(parentComponent, message, title, JOptionPane.PLAIN_MESSAGE, null,
                selecttionValues, selecttionValues[0]);
        UIManager.put("OptionPaneUI", defaultOptionPaneUI);
        return object;
}And then create your own MyBasicOptionPaneUI extending from javax.swing.plaf.basic.BasicOptionPaneUI with 2 methods overridden. The codes are copied from javax.swing.plaf.basic.BasicOptionPaneUI and modified to get rid of JComboBox.
public class MyBasicOptionPaneUI extends BasicOptionPaneUI
    public MyBasicOptionPaneUI()
        super();
    public static ComponentUI createUI(JComponent x) {
         return new MyBasicOptionPaneUI();
    protected Object getMessage()
        inputComponent = null;
        if (optionPane != null) {
            if (optionPane.getWantsInput()) {
                /* Create a user component to capture the input. If the
                   selectionValues are non null  with any size ,
                   it'll be a list, otherwise it'll be a textfield. */
                Object message = optionPane.getMessage();
                Object[] sValues = optionPane.getSelectionValues();
                Object inputValue = optionPane
                        .getInitialSelectionValue();
                JComponent toAdd;
                if (sValues != null) {
                        JList list = new JList(sValues);
                        JScrollPane sp = new JScrollPane(list);
                        list.setVisibleRowCount(10);
                        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                        if (inputValue != null)
                            list.setSelectedValue(inputValue, true);
                        list.addMouseListener(new ListSelectionListener());
                        toAdd = sp;
                        inputComponent = list;
                } else {
                    MultiplexingTextField tf = new MultiplexingTextField(20);
                    tf.setKeyStrokes(new KeyStroke[]{
                        KeyStroke.getKeyStroke("ENTER")});
                    if (inputValue != null) {
                        String inputString = inputValue.toString();
                        tf.setText(inputString);
                        tf.setSelectionStart(0);
                        tf.setSelectionEnd(inputString.length());
                    tf.addActionListener(new TextFieldActionListener());
                    toAdd = inputComponent = tf;
                Object[] newMessage;
                if (message == null) {
                    newMessage = new Object[1];
                    newMessage[0] = toAdd;
                } else {
                    newMessage = new Object[2];
                    newMessage[0] = message;
                    newMessage[1] = toAdd;
                return newMessage;
            return optionPane.getMessage();
        return null;
    private static class MultiplexingTextField extends JTextField
        private KeyStroke[] strokes;
        MultiplexingTextField(int cols)
            super(cols);
         * Sets the KeyStrokes that will be additional processed for
         * ancestor bindings.
        void setKeyStrokes(KeyStroke[] strokes)
            this.strokes = strokes;
        protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                                            int condition, boolean pressed)
            boolean processed = super.processKeyBinding(ks, e, condition,
                    pressed);
            if (processed && condition != JComponent.WHEN_IN_FOCUSED_WINDOW) {
                for (int counter = strokes.length - 1; counter >= 0;
                     counter--) {
                    if (strokes[counter].equals(ks)) {
                        // Returning false will allow further processing
                        // of the bindings, eg our parent Containers will get a
                        // crack at them.
                        return false;
            return processed;
    private class ListSelectionListener extends MouseAdapter
        public void mousePressed(MouseEvent e)
            if (e.getClickCount() == 2) {
                JList list = (JList) e.getSource();
                int index = list.locationToIndex(e.getPoint());
                optionPane.setInputValue(list.getModel().getElementAt(index));
    private class TextFieldActionListener implements ActionListener
        public void actionPerformed(ActionEvent e)
            optionPane.setInputValue(((JTextField) e.getSource()).getText());
}

Similar Messages

  • JOptionPane.showInputDialog with JTextarea?

    Hi,
    is it possible to put a JTextArea into a JOptionPane.showInputDialog?
    the reason i need to know is because my string is to long to fit into the current JOptionPane.showInputDialog.
    Greeting
    Grad_

    You could use your favorite component in other showXxxDialogs than the showInputDialog. Get the input on the component in an ActionListener or other appropriate event handler you've written for that component.

  • JOptionPane.showInputDialog with echo chars

    Is there any way to have use JOptionPane.showInputDialog() to have echo characters?
    so that when you type something in the dialog, you can only see ***** just like JPasswordField

    The [url http://java.sun.com/developer/JDCTechTips/]Beyond the Basics of JOptionPane article might give you some ideas..

  • Help with JOptionPane.showInputDialog

    Hi!!
    People here helped me before so trying my luck again:)
    In order to get information from people I use JOptionPane.showInputdialog,
    problem is if I need to get 2 different types of info I have to use
            naam = JOptionPane.showInputDialog(null, "Geef speler naam:");
            land = JOptionPane.showInputDialog(null, "Geef Land Speler:");Is there anyway to make this happen in 1 screen?
    Or do I have to make a new frame for that with textfields and such?
    if so, anyone got an example?

    im new here:) so.. New to Java Technology suits me
    well I guess.No it doesn't. New to Java forum is for classpath questions, simple compile time problems and lazy students to cross post their assigments into.
    Swing questions, such as the one you asked, should be asked in the Swing forum because the people who answer questions in there are more knowledgeable about Swing. Plus you will almost 100% likely to find working example codes from previous posts in the Swing forum for Swing related questions.
    Much more likely than in here anyway.

  • Strange problem with JOptionPane.showInputDialog

    I have a strange problem with JOptionPane.showInputDialog in that when I run a program anything that is typed in is displayed backwards, for example: I type this character > and this < is what is displayed.
    I've uninstalled the sdk and reinstalled it twice but that hasn't solved my problem and the java plug-in in the control panel is displaying the same symptoms.
    I did a search before posting this but all I got really was posts from people who wanted to reverse their text.
    Thanks for your help on this.

    Is it just the < and > characters?

  • Please help me! showInputDialog with specific Buttons

    Hi all,
    I'm from Germany and have some trouble with the JOptionPane package.
    Everything works fine, but I have a german operationsystem and i'm writing an 1.4 application in english.
    If I use a Optiondialog i can create my own buttontexts.
    String[] options = { "Yes", "No" };
    int n = JOptionPane.showOptionDialog(StartScreen.frame,
    "Do you really want to quit ?", // Fragetext
    "Are you sure ?", // Titel
    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, // Icon
    null, options, options[0]);
    if (n == JOptionPane.YES_OPTION) {
    Transfer.closeConnection();
    System.exit(0);
    That works, but here I see the german buttons, how can I choose specific Buttons here?
    String response = (String) JOptionPane.showInputDialog(
              contentpane, // parent
              "Who is your favorite chipmunk?", // message
              "Pick a Chipmunk", // dialog title
              JOptionPane.QUESTION_MESSAGE, // icon type
              null, // no explicit icon
              new String[] {                     // choices
                   "Alvin", "Simon", "Theodore"
              "Alvin"); // default choice
    Hope anyone can help me.
    Thanks

    in your main method :
    Locale.setDefault(Locale.UK);
    Then all default buttons will show in english.

  • JOptionPane.showInputDialog cancel brings up a blank box

    String name = JOptionPane.showInputDialog(
        null,
        "My message",
        "My title",
        null,
        null,
        null)  // real list of options deleted for brevityThis works okay, but when I press the cancel button, I get a blank warning JOptionPane (message box thingy)... how do I tailor the message in that? Been looking through the search results and API with little luck.

    handle it like so
    try
        String s = new JOptionPane.showInputDialog(null, "Enter input");
    catch(Exception ee)
        JOptionPane.showMessageDialog("Invalid input");
    }

  • Using JOptionPane.showInputDialog to return an integer

    I am currently using JOptionPane to return a string from the Object array i made with all possible choices.
         private static boolean determineService(){
              JLabel label;
              label=new JLabel("Please select which Service Model to use.",JLabel.CENTER);
              Object[] possibilities = {"AddressCleanse", "VIN", "PostalCode"};
              serviceModel = (String)JOptionPane.showInputDialog(
                                  null,
                                  label,
                                  "Select Service",
                                  JOptionPane.PLAIN_MESSAGE,null,
                                  possibilities,
                                  "AddressCleanse");
    //          If a string was returned, say so.
              if ((serviceModel != null) && (serviceModel.length() > 0)) {
                  System.out.println("You've selected " + serviceModel + "!");
                  setVariables();
                  return true;
              }else{
    //               If you're here, the return value was null/empty.
                   System.out.println("Null or Bad service selected!\n Exiting program.");
                   return false;
              }I would like to instead return the response as an integr so I can then use a switch, rather than recursive if, else if logic.
    Apparently java doesnt allow switches to use strings (like PHP does)
    any ideas?

    Just a question more than an answer: would using a hashmap ever work here? where the key is a string and the value is an (???) object that implements an interface that would allow you to call an appropriate method? Perhaps one could use the keySet() and toArray to build the Object array for the JOptionPane. I thought I read something about this somewhere, but am not sure....

  • JOptionPane.showInputDialog

    Hi,
    I have a question about JOptionPane.showInputDialog(...), there is a method that accepts an object array for its parameter, when the array size exceeds a certain bound the final dialog will contains a JList in it. When I click the item of the JList then click cancel the null will be returned, but when double clicking item and then cancel the item will be returned. Partial of my code is:
    String[] available = toSortedStringArray(mapColumn.keys());
    if (available.length == 0)
         return;
    Object selected =
         JOptionPane.showInputDialog(
              FilterControl.this,
              "Select Column",
    JOptionPane.QUESTION_MESSAGE,
              null,
              available,
              null);
    if (selected != null)
    When the dialog shows, double click one of the items in the JList and then click cancel, the selected will be the item, that's what we unexpected, the null returned will be expected.
    Who can help giving a hint about how to solve this problem?
    PS: One of the solutions is don't call this static method but write our own code or to create a class to extend the JOptionPane, but I think it is ineffective.

    It's a bug:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6428694

  • JOptionPane.showInputDialog Help!!!!

    Hello,
    I'm using JOptionPane.showInputDialog(Component parentComponent,
    Object message,
    String title,
    int messageType,
    Icon icon,
    Object[] selectionValues,
    Object initialSelectionValue ).
    which prompts the user to add some text and the same will be stored for later retrieval.
    In this case, JOptionPane pops up with a label, textfield,OK & Cancel buttons.
    Default focus is given to to the TextField.
    Is there anyway to get access to the TextField via code ?
    For example, if the user types "Hello World" in the given TextField, then I need to get the Text entered in
    the TextField in the following manner.
    String myStr = myJOptionPaneTextField().getText();
    System.out.println("Entered Text is "+ myStr);
    How can I Achieve the same ?
    Thanks in advance
    Regards
    vargav

    Why? At what point do you know you should manipulate the text? Usually, it would be when the user clicks OK, at which point it doesn't matter because the dialog is dismissed. So what kind of operations do you expect to be able to do?
    Aside from that, I'm not sure how to get the text field in the option pane, per se... It can be gotten by digging thru the pane's components til you find a text field. But you'd need to do that in a separate thread. So it's not really feasible to do that.... There is an alternative:
    The message is an object, and it can be an array of objects, which will all be added, and thus can include a message string and a text field...
    JTextField myfield = new JTextField();
    Object[] obj = new Object[2];
    obj[0] = "Enter some text here:";
    obj[1] = myfield;
    if(JOptionPane.showOptionDialog(obj, "Enter Text", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
       String value = myfield.getText();
    }Then you can do whatever you want with the text field... but the same problem is there, you have lost the dialog before you can do anything.

  • JOptionPane.showInputDialog without CANCEL Button

    How can I do a JOptionPane.showInputDialog without CANCEL Button.
    Besides if I press OK without tyoing anything, will a null String but returned?
    Thanks

    I don't think you can with an Input Dialog. Normally, you want to give the user a chance to cancel the operation. Here is an example using a Message Dialog. After the user hits OK, you can get the text from the text field.          JPanel p = new JPanel(new GridLayout(2,1));
              JTextField t = new JTextField();
              JLabel l = new JLabel("A message");
              p.add(l);
              p.add(t);
              JOptionPane.showMessageDialog(null,p,"Title",JOptionPane.PLAIN_MESSAGE);

  • JOptionPane.showInputDialog and Focus

    I have a program that allows the user to type in a String in a text box and when they hit the enter key the text will appear in a text area. I've also added a menu bar to the program. When the user clicks on File and then Connect from the menu bar I want a JOptionPane to pop up that asks for the user to type in a username and then prompt for a password. And I've gotten all of that to work. Now for the problem. I click on file from the menu bar and then connect and it prompts me for the username as it should. I am able to just type in a phrase in the text field of the username dialog box and hit the enter key and then it prompts me for my password. I am still able to type in a phrase in the text field of the password Dialog box, however when I hit the enter key, the Dialog box does not close as it did for the username Dialog box. It will still close if I click on the OK button, but just pressing the enter key does not close the Dialog box as it did when it prompted for a username. I'm thinking I need to direct the focus to the password dialog box, but not sure how to go about doing this. Any help in solving this problem would be greatly appreciated.
    Here is my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class TestJOptionPane extends JFrame implements ActionListener{
         private static int borderwidth = 570;
         private static int borderheight = 500;
         private JPanel p1 = new JPanel();
         private JMenu m1 = new JMenu("File");
         private JMenuBar mb1 = new JMenuBar();
         private JTextArea ta1 = new JTextArea("");
         private JTextField tf1 =new JTextField();
         private Container pane;
         private static String s1, username, password;
         private JMenuItem [] mia1 = {new JMenuItem("Connect"),new JMenuItem("DisConnect"),
              new JMenuItem("New..."), new JMenuItem ("Open..."), new JMenuItem ("Save"),
              new JMenuItem ("Save As..."), new JMenuItem ("Exit")};
    public TestJOptionPane (){
         pane = this.getContentPane();
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
         dispose();
    System.exit(0);
         setJMenuBar(mb1);
    mb1.add(m1);
    for(int j=0; j<mia1.length; j++){
         m1.add(mia1[j]);
    p1.setLayout( new BorderLayout(0,0));
    setSize(borderwidth, borderheight);
    pane.add(p1);
              p1.add(tf1, BorderLayout.NORTH);
              p1.add(ta1, BorderLayout.CENTER);
              this.show();
              tf1.addActionListener(this);
              for(int j=0; j<mia1.length; j++){
                   mia1[j].addActionListener(this);
         public void actionPerformed(ActionEvent e){
              Object source = e.getSource();
              if(source.equals(mia1 [0])){
                   username = JOptionPane.showInputDialog(pane, "Username");
                   password = JOptionPane.showInputDialog(pane, "Password");
              if(source.equals(tf1)){
                   s1=tf1.getText();
                   ta1.append(s1+"\n");
                   s1="";
                   tf1.setText("");
         public static void main(String args[]){
              TestJOptionPane test= new TestJOptionPane();
    }

    But using JOptionPane doesn't get the focus when you call itworks ok like this
    import javax.swing.*;
    import java.awt.event.*;
    class Testing
      public Testing()
        final JPasswordField pwd = new JPasswordField(10);
        ActionListener al = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            pwd.requestFocusInWindow();}};
        javax.swing.Timer timer = new javax.swing.Timer(250,al);
        timer.setRepeats(false);
        timer.start();
        int action = JOptionPane.showConfirmDialog(null, pwd,"Enter Password",JOptionPane.OK_CANCEL_OPTION);
        if(action < 0)JOptionPane.showMessageDialog(null,"Cancel, X or escape key selected");
        else JOptionPane.showMessageDialog(null,"Your password is "+new String(pwd.getPassword()));
        System.exit(0);
      public static void main(String args[]){new Testing();}
    }

  • JOptionPane.showInputDialog error checking?

    menu = JOptionPane.showInputDialog("What would you like to do next: \n" +
    "1: Enter another person (" + (data.length - index - 1) + " entries left)\n" +
    "2: Display data sorted by First Name\n" +
    "3: Display data sorted by Last Name\n" +
    "4: Display data sorted by Birth Date\n" +
    "5: Search data by First Name\n" +
    "6: Search data by Last Name\n" +
    "7: Search data by Birth Date\n\n" +
    "0: Exit");How can I error check that to make only those values will be entered. I thought I would be able to say something like, if(menu != "0") and so on, but that doesn't seem to work, neither does if(menu == null). Thanks in advance for any help, I am probably just doing something stupid.

    You will get more chance on a suitable answer if you post this Swing related question in the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57

  • Setting focus in JOptionPane.showInputDialog

    Hi!
    For usability I want to set the focus to the dialog that pops up if i call JOptionPane.showInputDialog(...).
    Someone an idea how this works?
    cu

    Hi...
    I am facing exactly the same problem... If you have found a solution, please contact me at:
    [email protected]
    Regards.

  • Custom icon for JOptionPane.showInputDialog

    As a novice who's wading through Deitel's 'Java how to program', using java2 and j2sdk1.4.1 on JCreator Pro. I want to use my own icons on a small proggie i've written. I know that the format is:
    showInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue)
    however this doesn't tell me how to write the code. how do i change the default '?' icon for my own icon?
    thanks for any help
    rgds
    adambi

    This should help you also
                ImageIcon ico = new ImageIcon("drag2.jpeg");
                Frame frame = new Frame();
                Object[] options = {"Yes, please",
                        "No, thanks",
                        "No eggs, no ham!"};
              JOptionPane.showInputDialog(frame,
              "What some eggs ?.",
              "My title",JOptionPane.ERROR_MESSAGE,ico,options,
        options[2]);also here is a good link for ya on dialogs
    http://java.sun.com/j2se/1.4/docs/api/
    GOOD LUCK

Maybe you are looking for

  • Show Top n Values on One Line

    I have my SSRS report to show the top 3 volumes by physician. My problem is it shows them in three lines going down, even though the code is in one cell. Such as: Dr Smith Dr Johnson Dr James I need it to show as Dr Smith, Dr Johnson, Dr James (all o

  • Running x in a xen domU

    Hey guys, I am trying to configure myself what I would like to consider a poor mans sonos using xbmc and yatse to control it remotely. So far, I have managed to install arch as a domu vm and I am passing through a soundcard for obvious purposes.  Fro

  • ROS supplier not transferring in EBP

    Dear SRM Experts, We are working in SRM5.0 with support pack SAPKIBK008. I have configured ROS and EBP on different client & have maintained following settng: 1. Activated all ROS services in both client. 2. Service user created in ROS with AP_EC_BBP

  • Uncaught exception: java.lang.IllegalArgumentException

    I have the 8320, and every time I try and text, it wont let me and this error pops up, then i have to go into the options and go to sms and change the "network to send over" from GSM to GPRS and then back over to GSM and then save for me to be able t

  • NetStumbler 4 and WLC 5.1

    Hello, I'm currently testing the WLC 2106 updated to 5.1.151.0 and NetStumbler 0.4.0 (http://downloads.netstumbler.com/downloads/netstumblerinstaller_0_4_0.exe) The WLC don't recognize NetStumbler... Is-there a new signature for this version ? I have