Apply special filter to a JTextField : Actions « Swing JFC « Java

Apply special filter to a JTextField


import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

class JTextFieldFilter extends PlainDocument {
  public static final String NUMERIC = "0123456789";

  protected String acceptedChars = null;

  protected boolean negativeAccepted = false;

  public JTextFieldFilter() {

  public JTextFieldFilter(String acceptedchars) {
    acceptedChars = acceptedchars;

  public void setNegativeAccepted(boolean negativeaccepted) {
    if (acceptedChars.equals(NUMERIC)) {
      negativeAccepted = negativeaccepted;
      acceptedChars += "-";

  public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (str == null)

    for (int i = 0; i < str.length(); i++) {
      if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)

    if (negativeAccepted && str.indexOf("-") != -1) {
      if (str.indexOf("-") != 0 || offset != 0) {

    super.insertString(offset, str, attr);

public class Main extends JFrame{

  public static void main(String[] argv) throws Exception {
    new Main();

  public Main() {
    JTextField tf1, tf1b, tf1c, tf2, tf3;
    JLabel l1, l1b, l1c, l2, l3;

    setLayout(new FlowLayout());
    l1 = new JLabel("only numerics");
    tf1 = new JTextField(10);
    tf1.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC));


Related examples in the same category

1.Action DemoAction Demo
2.Creating an Action
3.Enabling an Action
4.UseActions: MenuUseActions: Menu
5.Action events are fired by subclasses of AbstractButton and includes buttons, checkboxes, and menus.
6.Listing the Actions in a Component
7.Sharing an InputMap or an ActionMap Between Two Components
8.Listing the Key Bindings in a Component
9.A text component has an action map with actions and keymaps with actions
10.extends AbstractAction to create your won actionextends AbstractAction to create your won action