在JOptionPane上设置DocumentFilter [英] Set DocumentFilter on JOptionPane

查看:114
本文介绍了在JOptionPane上设置DocumentFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用:

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

以获得用户对问题的答复;对话框被设置为显示响应的文本字段.我想将响应中允许的字符限制为仅字母数字和"_".是否可以在文本字段上安装DocumentFilter,而无需从头开始实现我自己的自定义对话框?

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?

推荐答案

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

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

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

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.

以下是示例:

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());
}

这篇关于在JOptionPane上设置DocumentFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆