Java文本框只有一行数据,Java只允许输入数目字的文本框
Java只允許輸入數字的文本框
package com.han;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* Customized fields can easily be created by extending the model
* and changing the default model provided. For example,
* the following piece of code will create a field that holds only
* digit characters. It will work even if text is pasted into from
* the clipboard or it is altered via programmatic changes.
* @author HAN
*
*/
public class DigitOnlyField extends JTextField {
/**
*
*/
private static final long serialVersionUID = 8384787369612949227L;
public DigitOnlyField(int cols) {
// super() 可以被自動調用,但是有參構造方法并不能被自動調用,只能依賴
// super關鍵字顯示地調用父類的構造方法
super(cols);
}
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
/**
*
*/
private static final long serialVersionUID = -4170536906715361215L;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
char[] upper = str.toCharArray();
String filtered = "";
for (int i = 0; i < upper.length; i++) {
if (Character.isDigit(Character.codePointAt(upper, i))){
filtered += upper[i];
}
}
super.insertString(offs, filtered, a);
}
}
}
總結
以上是生活随笔為你收集整理的Java文本框只有一行数据,Java只允许输入数目字的文本框的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 内存超频,让你的电脑提速不止一点点
- 下一篇: 内存评测大揭秘:闪电光速 vs 巨无霸,