java 文本框输入限制
时间: 2023-11-24 10:59:40 浏览: 115
在 Java 中,可以使用 JTextField 组件来实现文本框的输入限制。下面是一些限制的例子:
1. 限制文本框只能输入数字
```java
JTextField textField = new JTextField();
textField.setDocument(new NumberOnlyDocument());
```
其中 NumberOnlyDocument 是一个自定义的 Document 类,代码如下:
```java
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
public class NumberOnlyDocument extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if (string == null) {
return;
}
String newValue;
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
newValue = sb.toString();
if (newValue.matches("\\d*")) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (text == null) {
return;
}
String newValue;
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
newValue = sb.toString();
if (newValue.matches("\\d*")) {
super.replace(fb, offset, length, text, attrs);
}
}
}
```
2. 限制文本框只能输入特定长度的字符串
```java
JTextField textField = new JTextField(10);
textField.setDocument(new LengthLimitedDocument(10));
```
其中 LengthLimitedDocument 是一个自定义的 Document 类,代码如下:
```java
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class LengthLimitedDocument extends PlainDocument {
private int limit;
public LengthLimitedDocument(int limit) {
this.limit = limit;
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (getLength() + str.length() <= limit) {
super.insertString(offs, str, a);
}
}
@Override
public void replace(int offs, int len, String str, AttributeSet a) throws BadLocationException {
if (getLength() - len + str.length() <= limit) {
super.replace(offs, len, str, a);
}
}
}
```
这些代码可以在文本框中实现输入限制。
阅读全文