Using DocumentFilter.FilterBypass

For instance, here’s an SSCCE with a DocumentFilter which prevents the user from typing numbers into the document but allows the Swing Timer to do so. import java.awt.event.*; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.text.*; public class DocFilterPanel extends JPanel { private JTextArea textArea = new JTextArea(12, 50); private MyDocFilter myDocFilter = new MyDocFilter(); public DocFilterPanel() … 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

JTextField limiting character amount input and accepting numeric only

You’re on the right track, except you will want to use a DocumentFilter instead of implementing your own document. MDP’s Weblog has a number of excellent examples (including limiting the length and character type). Now to the your question, you could create cascading filter, where you could chain a series of filters together. This would … Read more

java change the document in DocumentListener

DocumentListener is really only good for notification of changes and should never be used to modify a text field/document. Instead, use a DocumentFilter Check here for examples FYI The root course of your problem is that the DocumentListener is notified WHILE the document is been updated. Attempts to modify the document (apart from risking a … Read more