请教一个问题 java中哪个控件,可以限制每行只能输入10个英文字符

来源:百度知道 编辑:UC知道 时间:2024/05/21 12:22:00
还可以取得每行的内容

可以给出代码么

JTextField

import java.awt.FlowLayout;

import javax.print.attribute.AttributeSet;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class Test2 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
JTextField field = new JTextField(15);
field.setDocument(new FixedLengthDocument(10));

frame.add(field);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}

public static class FixedLengthDocument extends PlainDocument {
private int length;
public FixedLengthDocument(int length) {
super();
this.length = length;
}

@Override
public void insertString(int offs, String str,