I've seen that this is possible in other types of dialog windows such as "showConfirmDialog", where one can specify the amount of buttons and their names; but is this same functionality achievable when using "showInputDialog"? I couldn't seem to find this type of thing in the API. Perhaps I just missed it, but any help is appreciated.
Asked
Active
Viewed 2.8k times
6
-
1Yes it is possible. With the showOptionDialog, you can tailor the option pane much more freely. Edit: as @Maroun shows you in his answer. 1+ to his answer. – Hovercraft Full Of Eels May 12 '13 at 19:10
3 Answers
16
Just add a custom JPanel as a message to JOptionPane.showOptionDialog()
:
String[] options = {"OK"};
JPanel panel = new JPanel();
JLabel lbl = new JLabel("Enter Your name: ");
JTextField txt = new JTextField(10);
panel.add(lbl);
panel.add(txt);
int selectedOption = JOptionPane.showOptionDialog(null, panel, "The Title", JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options , options[0]);
if(selectedOption == 0)
{
String text = txt.getText();
// ...
}
4
JOptionPane.showInputDialog()
returns the string the user has entered if the user clicks "OK" and returns null
otherwise. See this:
Returns: user's input, or null meaning the user canceled the input
You can't do this using showInputDialog()
However, you can use JOptionPane#showOptionDialog():
Object[] buttons = {"OK"};
int res = JOptionPane.showOptionDialog(yourFrame,
"YourMessage","YourTitle",
JOptionPane....,
JOptionPane..., null, buttons , buttons[0]);
As @HovercraftFullOfEels stated on the comments, you can add JTextField
to the dialog and achieve this.

Maroun
- 94,125
- 30
- 188
- 241
-
1
-
I'm kind of new to Java, how do I get the user-input using this method? – Coffee_Table May 12 '13 at 19:15
-
No, `showOptionDialog` is something different from `showInputDialog`! – Eng.Fouad May 12 '13 at 19:15
-
@Eng.Fouad : yes, is there a way to do this and still have the box for user-input? – Coffee_Table May 12 '13 at 19:17
-
2You can add a JTextField or a JPanel with a JTextField to this dialog with ease. So this solution is still very much a valid solution. – Hovercraft Full Of Eels May 12 '13 at 19:18