Search code examples
javaswingjoptionpanejdialog

Pop up Swing window with both option and textfield


Given such codes:

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");

enter image description here

You can see that it pop up a window with options. However, can I have an JTextField paralleled with that? So I can get the inputs both from the option and the text field.


Solution

  • In a round about way, yes...

    Breakfast

    JPanel fields = new JPanel(new GridLayout(2, 1));
    JTextField field = new JTextField(10);
    JComboBox<String> comboBox = new JComboBox<>(new String[]{"ham", "spam", "yam"});
    
    fields.add(field);
    fields.add(comboBox);
    
    int result = JOptionPane.showConfirmDialog(null, fields, "Breakfast", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    switch (result) {
        case JOptionPane.OK_OPTION:
            // Process the results...
            break;
    }
    

    People either forget or don't realise that if you pass a JComponent to a JOptionPane as the message parameter, it will be added to the JOptionPane, making it really rather flexibile and powerful