Search code examples
javaswingjoptionpane

Using an ArrayList with JOptionPane.showInputDialog


I'm currently having the situation that I need to provide the user of my application a dialog with a number of options to choose from. Example:

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Complete the sentence:\n"
                    + "\"Green eggs and...\"",
                    "Customized Dialog",
                    JOptionPane.PLAIN_MESSAGE,
                    icon,
                    possibilities,
                    "ham");

It seemed that JOptionPane.showInputDialog could do this. However it seems that it can only use an array of Objects for the options to choose from, but in my case the list is not static, so I can't define an array, since I have an ArrayList with a variable size. The second point is that it doesn't give me the selected index back when I call it, but I neeed this since I have another complex list in the background that contains the values defined by the index of the option that was selected. Is it somehow possible to push a dynamic list to this dialog or is there any other, more elegant and flexible way of doing what I need?

Thanks a lot in advance.


Solution

  • You could use indexOf() on your List to determine the index based on what JOptionPane returns. The example below demonstrates this and could be expanded to work with a larger list of options.

    List<String> optionList = new ArrayList<String>();
    optionList.add("Ham");
    optionList.add("Eggs");
    optionList.add("Bacon");
    Object[] options = optionList.toArray();
    Object value = JOptionPane.showInputDialog(null, 
                                               "Favorite Food", 
                                               "Food", 
                                                JOptionPane.QUESTION_MESSAGE, 
                                                null,
                                                options, 
                                                options[0]);
    
    int index = optionList.indexOf(value);