その列に特定のセルエディタを設定するだけで、間違った文字を入力できなくなります。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();
}
});
}
}