Set DocumentFilter on JOptionPane

為{幸葍}努か 提交于 2020-01-24 13:05:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!