Java Swing How to - extends NavigationFilter for JTextField








Question

We would like to know how to extends NavigationFilter for JTextField.

Answer

import java.awt.event.ActionEvent;
//from   w  w  w .  j a  v  a  2  s  .c  o m
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
import javax.swing.text.NavigationFilter;
import javax.swing.text.Position;

public class Main {

  public static void main(String[] args) throws Exception {
    JTextField textField = new JTextField("Prefix_", 20);
    textField.setNavigationFilter(new NavigationFilterPrefixWithBackspace(7,
        textField));
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(textField);
    frame.pack();
    frame.setVisible(true);
  }
}

class NavigationFilterPrefixWithBackspace extends NavigationFilter {

  private int prefixLength;
  private Action deletePrevious;

  public NavigationFilterPrefixWithBackspace(int prefixLength,
      JTextComponent component) {
    this.prefixLength = prefixLength;
    deletePrevious = component.getActionMap().get("delete-previous");
    component.getActionMap().put("delete-previous", new BackspaceAction());
    component.setCaretPosition(prefixLength);
  }

  @Override
  public void setDot(NavigationFilter.FilterBypass fb, int dot,
      Position.Bias bias) {
    fb.setDot(Math.max(dot, prefixLength), bias);
  }

  @Override
  public void moveDot(NavigationFilter.FilterBypass fb, int dot,
      Position.Bias bias) {
    fb.moveDot(Math.max(dot, prefixLength), bias);
  }
  class BackspaceAction extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
      JTextComponent component = (JTextComponent) e.getSource();
      if (component.getCaretPosition() > prefixLength) {
        deletePrevious.actionPerformed(null);
      }
    }
  }

}