2

I'm using:

String s = JOptionPane.showInputDialog(...);

to get a response back from the user to a question; the dialog is set up to display a text field for the response. I'd like to limit the characters allowed in the response to alphanumeric and '_' only. Is it possible to install a DocumentFilter on the text field without implementing my own custom dialog from scratch?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Paul Carlisle
  • 415
  • 1
  • 5
  • 11

2 Answers2

3

Access the autocreated text field of JOptionPane is theoretically possible, but it's IMHO wrong way.

Here is the better solution: JOptionPane has a hidden feature: it accepts also Swing components as messages. So you need to create a panel with lable and text field (with your DocumentFilter) and pass it to a confirm dialog. After confirmation you can read the text from your text field.

Here is sample:

JPanel p = new JPanel(new FlowLayout());
JTextField fld = new JTextField(10);
// set document filter for 'fld' here
p.add(new JLabel("Enter text: "));
p.add(fld);
int val = JOptionPane.showConfirmDialog(null, p, "Test", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null);
if (JOptionPane.OK_OPTION == val) {
  System.out.println("Text: "  + fld.getText());
}
Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48
2

Not sure how to add a DocumentFilter to the text field document directly.

See Stopping Automatic Dialog Closing for a different approach.

camickr
  • 321,443
  • 19
  • 166
  • 288