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?

4

2 回答 2

3

理论上可以访问 JOptionPane 的自动创建的文本字段,但恕我直言,这是错误的方式。

这是更好的解决方案:JOptionPane 有一个隐藏的特性:它也接受 Swing 组件作为消息。因此,您需要创建一个带有标签和文本字段的面板(使用 DocumentFilter)并将其传递给确认对话框。确认后,您可以从文本字段中读取文本。

这是示例:

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());
}
于 2013-02-11T15:59:21.507 回答
2

不确定如何直接将 DocumentFilter 添加到文本字段文档。

有关不同的方法,请参阅停止自动关闭对话框。

于 2013-02-11T15:55:55.747 回答