问题
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?
回答1:
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());
}
回答2:
Not sure how to add a DocumentFilter to the text field document directly.
See Stopping Automatic Dialog Closing for a different approach.
来源:https://stackoverflow.com/questions/14814336/set-documentfilter-on-joptionpane