JTable单元格用户输入字符限制及过滤需求咨询
Solution for JTable Input Validation (Allowed Characters + Length Limit)
Got it, let's build this validation for your JTable user data entry app. We'll use Swing's DocumentFilter to enforce both the allowed character set and maximum 10-character limit—this is the cleanest way to handle real-time input restrictions in JTable cells.
Step 1: Create a Custom DocumentFilter
This filter will check every character being entered, block disallowed ones, and cap the total length at 10.
import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; public class RestrictedInputFilter extends DocumentFilter { // Allowed characters: A-G, #, -, [, ] (case-insensitive by default) private static final String ALLOWED_CHARS = "ABCDEFG#-[]"; private static final int MAX_LENGTH = 10; @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { // Calculate the potential new length after input int newLength = fb.getDocument().getLength() - length + text.length(); // First, enforce the max length limit if (newLength > MAX_LENGTH) { int allowedRemaining = MAX_LENGTH - (fb.getDocument().getLength() - length); if (allowedRemaining > 0) { text = text.substring(0, allowedRemaining); } else { // No space left, reject the input entirely return; } } // Filter out any characters not in our allowed set StringBuilder filteredText = new StringBuilder(); for (char c : text.toCharArray()) { if (ALLOWED_CHARS.indexOf(Character.toUpperCase(c)) != -1) { filteredText.append(c); } // Disallowed chars get silently ignored } // Pass the cleaned-up text to the parent class for insertion super.replace(fb, offset, length, filteredText.toString(), attrs); } }
Step 2: Create a Custom Table Cell Editor
We'll wrap a JTextField with our filter and use it as the cell editor for your JTable.
import javax.swing.DefaultCellEditor; import javax.swing.JTextField; import javax.swing.text.PlainDocument; public class RestrictedCellEditor extends DefaultCellEditor { public RestrictedCellEditor() { super(new JTextField()); JTextField textField = (JTextField) getComponent(); PlainDocument doc = (PlainDocument) textField.getDocument(); doc.setDocumentFilter(new RestrictedInputFilter()); } }
Step 3: Apply the Editor to Your JTable
Assign this custom editor to the columns that need the restrictions. You can target specific columns or set it as the default for all columns.
Example: Apply to a Specific Column
// Assume your JTable is named 'userDataTable' int targetColumn = 1; // Replace with your actual column index userDataTable.getColumnModel().getColumn(targetColumn).setCellEditor(new RestrictedCellEditor());
Example: Set as Default Editor for All Columns
userDataTable.setDefaultEditor(Object.class, new RestrictedCellEditor());
Quick Notes
- Case Sensitivity: The current code accepts both uppercase and lowercase (by converting input to uppercase for checking). If you want to restrict to only uppercase, remove
Character.toUpperCase()from the filter. - Copy-Paste Handling: This setup automatically cleans up pasted text—truncating it to 10 characters and stripping out disallowed characters.
- Immediate Feedback: Users won't see invalid characters appear in the cell at all, which makes the validation feel intuitive rather than frustrating.
内容的提问来源于stack exchange,提问作者Nirmitha
相关产品推荐
相关产品推荐

