我想让我的j表列限制字符,只允许16个字符。我尝试了各种方法没有任何作用。任何人都可以帮助我吗?。
答案 0 :(得分:1)
在此处找到答案https://community.oracle.com/thread/1482301
“自定义单元格编辑器 http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#validtext 和JTextField上的自定义文档
一个值得千言万语的例子“
import java.awt.*;
import javax.swing.*;
public class Test2 extends JFrame {
public Test2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = getContentPane();
String[] head = {"One","Two","Three"};
String[][] data = {{"R1-C1", "12345678", "R1-C3"},
{"R2-C1", "R2-C2", "R2-C3"},
{"R3-C1", "R3-C2", "R3-C3"}};
JTable jt = new JTable(data, head);
content.add(new JScrollPane(jt), BorderLayout.CENTER);
JTextField jtf = new JTextField();
jtf.setDocument(new LimitedPlainDocument(10));
jt.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(jtf));
setSize(300,300);
}
public static void main(String[] args) { new Test2().setVisible(true); }
}
class LimitedPlainDocument extends javax.swing.text.PlainDocument {
private int maxLen = -1;
/** Creates a new instance of LimitedPlainDocument */
public LimitedPlainDocument() {}
public LimitedPlainDocument(int maxLen) { this.maxLen = maxLen; }
public void insertString(int param, String str,
javax.swing.text.AttributeSet attributeSet)
throws javax.swing.text.BadLocationException {
if (str != null && maxLen > 0 && this.getLength() + str.length() > maxLen) {
java.awt.Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(param, str, attributeSet);
}
}
答案 1 :(得分:0)
这就是我做的事情
电话:
JTable table = new JTable();
JTextField textField = new JTextField();
limitCharacters(jtf, 16);
table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(jtf));
limitCharacters方法:
private void limitCharacters(JTextField textField, final int limit) {
PlainDocument document = (PlainDocument) textField.getDocument();
document.setDocumentFilter(new DocumentFilter() {
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset,
int length, String text, AttributeSet attrs)
throws BadLocationException {
String string = fb.getDocument().getText(0,
fb.getDocument().getLength())
+ text;
if (string.length() <= limit)
super.replace(fb, offset, length, text, attrs);
}
});
}