只需在该列上设置一个不允许输入错误字符的特定单元格编辑器。可以肯定的是,我还将TableModel
通过正确覆盖来验证您的输入setValueAt(Object, int, int)
:
这是一个仅允许从 A 到 Z 和 a 到 z 的字符的示例:
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
public class TestTable {
private static final String ALPHA_ONLY_REGEXP = "\\p{Alpha}*";
private static final String NONALPHA_REGEXP = "[^\\p{Alpha}]+";
private int ALPHA_ONLY_COLUMN_INDEX = 2;
protected String validateAndFixString(String string) {
if (!string.matches(ALPHA_ONLY_REGEXP)) {
string = string.replaceAll(NONALPHA_REGEXP, "");
}
return string;
}
protected void initUI() {
final DefaultTableModel model = new DefaultTableModel() {
@Override
public void setValueAt(Object aValue, int row, int column) {
if (column == ALPHA_ONLY_COLUMN_INDEX) {
if (aValue != null) {
aValue = validateAndFixString((String) aValue);
}
}
super.setValueAt(aValue, row, column);
}
};
for (int i = 0; i < 5; i++) {
model.addColumn("Col-" + (i + 1));
}
for (int i = 0; i < 200; i++) {
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < 5; j++) {
if (j == ALPHA_ONLY_COLUMN_INDEX) {
row.add("AlphabetOnly");
}
row.add("New cell - " + (j + 1));
}
model.addRow(row);
}
JTable table = new JTable(model);
JTextField alphaOnly = new JTextField();
((PlainDocument) alphaOnly.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
string = validateAndFixString(string);
super.insertString(fb, offset, string, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
text = validateAndFixString(text);
super.replace(fb, offset, length, text, attrs);
}
});
table.getColumnModel().getColumn(ALPHA_ONLY_COLUMN_INDEX).setCellEditor(new DefaultCellEditor(alphaOnly));
JFrame frame = new JFrame(TestTable.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestTable().initUI();
}
});
}
}