How to restrict the JTextField to a x number of characters

You should use a DocumentFilter as per this tutorial. For example: import javax.swing.*; import javax.swing.text.*; public class JTextFieldLimit2 extends JPanel{ JTextField textfield = new JTextField(5); public JTextFieldLimit2() { PlainDocument doc = (PlainDocument) textfield.getDocument(); doc.setDocumentFilter(new TextLengthDocFilter(3)); add(textfield); } private class TextLengthDocFilter extends DocumentFilter { private int maxTextLength; public TextLengthDocFilter(int maxTextLength) { this.maxTextLength = maxTextLength; } private … Read more

Jtextfield and keylistener

Don’t use KeyListener on text components, there are a rafter of issues (not been notified, mutation exceptions, not been notified when the user pastes something into the field), instead, you should be using a DocumentFilter For example… import java.awt.EventQueue; import java.awt.GridBagLayout; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; … Read more

jTextField accept only alphabet and white space

Use a DocumentFilter, here is an example I made, it will only accept alphabetic characters and white spaces: import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import javax.swing.text.DocumentFilter.FilterBypass; public class Test { public Test() { initComponents(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void … Read more

Only allowing numbers and a symbol (-) to be typed into a JTextField

Use DocumentFilter: NumberOnlyFilter.java: import javax.swing.*; import javax.swing.text.*; import java.util.regex.*; public class NumberOnlyFilter extends DocumentFilter { public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { StringBuilder sb = new StringBuilder(); sb.append(fb.getDocument().getText(0, fb.getDocument().getLength())); sb.insert(offset, text); if(!containsOnlyNumbers(sb.toString())) return; fb.insertString(offset, text, attr); } public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) … Read more