【发布时间】:2015-03-27 13:50:12
【问题描述】:
我正在开发一些计算器,所以上面的JTextField只能有一些字符。
实现这一目标的最佳方法是什么?
假设我有这个char[] values = 0,1,2,3,4,5,6,7,8,9,+,-,*,/,(,),.,,这些是用户可以输入的值。
【问题讨论】:
标签: java swing jtextfield
我正在开发一些计算器,所以上面的JTextField只能有一些字符。
实现这一目标的最佳方法是什么?
假设我有这个char[] values = 0,1,2,3,4,5,6,7,8,9,+,-,*,/,(,),.,,这些是用户可以输入的值。
【问题讨论】:
标签: java swing jtextfield
使用JFormattedTextField。您可以将MaskFormatter 与setValidCharacters(...) 方法一起使用,并指定一个包含有效字符的字符串。
阅读 Using a MaskFormatter 上的 Swing 教程部分了解更多信息。
或者另一种方法是使用带有DocumentFilter 的JTextField。阅读Implementing a DocumentFilter 上的 Swing 教程了解更多信息。
【讨论】:
已经有几个像你这样的问题已经解决了:
Filter the user's keyboard input into JTextField (swing)
根据这些,您应该使用 DocumentFilter 或 JFormattedTextField。
【讨论】:
char[] 作为有效输入的示例
最终我设法创建了自己的JTextField,它的实现方式如下:
public class MyTextField extends JTextField {
//final value for maximum characters
private final int MAX_CHARS = 20;
/**
* A regex value which helps us to validate which values the user can enter in the input
*/
private final String REGEX = "^[\\d\\+\\/\\*\\.\\- \\(\\)]*$";
public MyTextField(){
//getting our text as a document
AbstractDocument document = (AbstractDocument) this.getDocument();
/**
* setting a DocumentFilter which helps us to have only the characters we need
*/
document.setDocumentFilter(new DocumentFilter() {
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
String text = fb.getDocument().getText(0, fb.getDocument().getLength());
text += str;
if ((fb.getDocument().getLength() + str.length() - length) <= MAX_CHARS && text.matches(REGEX)){
super.replace(fb, offs, length, str, a);
}
}
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
String text = fb.getDocument().getText(0, fb.getDocument().getLength());
text += str;
if ((fb.getDocument().getLength() + str.length()) <= MAX_CHARS && text.matches(REGEX)){
super.insertString(fb, offs, str, a);
}
}
});
}
}
【讨论】: