-2

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
chrisTina
  • 2,298
  • 9
  • 40
  • 74

1 Answers1

3

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • This looks cool. Can you make a little change so that the user can only either type in in the `textfield` or choose the from the `comboBox`? Set the other one unable when one of them has input or is choosen. – chrisTina Dec 17 '14 at 05:04
  • 1
    Yes, you could do that – MadProgrammer Dec 17 '14 at 05:06
  • 3
    Okay, what part of your original question asked for that? No offense, we're not your code monkeys... – MadProgrammer Dec 17 '14 at 05:16
  • *"Can you make a little change so that the user can only either type in in the textfield or choose the from the `comboBox`?"* Why not just show an **editable** `JComboBox` instead of the pair of components? – Andrew Thompson Dec 17 '14 at 06:17