Apply special filter to a JTextField in Java

Description

The following code shows how to apply special filter to a JTextField.

Example


     /*from   w  w  w . j av  a2  s  .  c  om*/


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() {
    this(NUMERIC);
  }

  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)
      return;

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

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

    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);
    getContentPane().add(l1);
    getContentPane().add(tf1);
    tf1.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC));
    setSize(300,300);
    setVisible(true);
  }
}

The code above generates the following result.

Apply special filter to a JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer