只能输入4位半角数字的JTextField中输入全角字符时会消去已有的数字。public class JTextFieldDemo extends JFrame {
JTextField jTextField = new JTextField() ;
JTextFieldDemo(){
this.setSize(200,300);
this.getContentPane().setLayout(new BorderLayout());
jTextField.setDocument(new TextFormatDigit(4));
this.getContentPane().add(BorderLayout.CENTER, jTextField);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JTextFieldDemo j = new JTextFieldDemo();
j.show();
}
}
public class TextFormatDigit extends PlainDocument{ private Pattern p = Pattern.compile("[1-9]{0}[0-9]{0,10}");
private Matcher m = p.matcher("");
private int maxLength = 0;
public TextFormatDigit() { }
public TextFormatDigit(int maxLength) {
this.maxLength = maxLength;
}
public void insertString(int offs, String str, AttributeSet attributeSet) throws BadLocationException { if (str == null) { return; }
if(str.getBytes().length > 1){
super.insertString(offs, "", attributeSet);
return;
} super.insertString(offs, str, attributeSet);
}
}是否是java本身的问题?
JTextField jTextField = new JTextField() ;
JTextFieldDemo(){
this.setSize(200,300);
this.getContentPane().setLayout(new BorderLayout());
jTextField.setDocument(new TextFormatDigit(4));
this.getContentPane().add(BorderLayout.CENTER, jTextField);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JTextFieldDemo j = new JTextFieldDemo();
j.show();
}
}
public class TextFormatDigit extends PlainDocument{ private Pattern p = Pattern.compile("[1-9]{0}[0-9]{0,10}");
private Matcher m = p.matcher("");
private int maxLength = 0;
public TextFormatDigit() { }
public TextFormatDigit(int maxLength) {
this.maxLength = maxLength;
}
public void insertString(int offs, String str, AttributeSet attributeSet) throws BadLocationException { if (str == null) { return; }
if(str.getBytes().length > 1){
super.insertString(offs, "", attributeSet);
return;
} super.insertString(offs, str, attributeSet);
}
}是否是java本身的问题?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货