Java/Swing JFC/Document Event — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:39, 1 июня 2010

An extension of PlainDocument that restricts the length of its content

  

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
public class MaxLengthDocument extends PlainDocument {
  private int max;
  public MaxLengthDocument(int maxLength) {
    max = maxLength;
  }
  public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
    if (getLength() + str.length() > max)
      java.awt.Toolkit.getDefaultToolkit().beep();
    else
      super.insertString(offset, str, a);
  }
}
class MainClass{
  public static void main(String[] a){
      Document doc = new MaxLengthDocument(5); // set maximum length to 5
      JTextField field = new JTextField(doc, "", 8);
      JPanel flowPanel = new JPanel();
      flowPanel.add(field);
      JFrame frame = new JFrame("MaxLengthDocument demo");
      frame.setContentPane(flowPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(160, 80);
      frame.setVisible(true);
  }
}





Bind a keystroke to shift-space

   

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField(10);
    
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("shift pressed SPACE"), "actionName");
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}





Disable a character so that no action is invoked.

   
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField(10);
    
    component.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("typed X"), "none");

    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}





Document ElementIterator Demo

  
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
public class ElementSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Element Example");
    Container content = frame.getContentPane();
    final JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    JButton button = new JButton("Show Elements");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Document document = textArea.getDocument();
        ElementIterator iterator = new ElementIterator(document);
        Element element = iterator.first();
        while (element != null) {
          System.out.println(element.getStartOffset());
          element = iterator.next();
        }
      }
    };
    button.addActionListener(actionListener);
    content.add(scrollPane, BorderLayout.CENTER);
    content.add(button, BorderLayout.SOUTH);
    frame.setSize(250, 250);
    frame.setVisible(true);
  }
}





Document Event Demo

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * DocumentEventDemo.java is a 1.4 example that
 * requires no other files.
 */
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
public class DocumentEventDemo extends JPanel 
                               implements ActionListener {
    JTextField textField;
    JTextArea textArea;
    JTextArea displayArea;
    public DocumentEventDemo() {
        super(new GridBagLayout());
        GridBagLayout gridbag = (GridBagLayout)getLayout();
        GridBagConstraints c = new GridBagConstraints();
        JButton button = new JButton("Clear");
        button.addActionListener(this);
        textField = new JTextField(20);
        textField.addActionListener(new MyTextActionListener());
        textField.getDocument().addDocumentListener(new MyDocumentListener());
        textField.getDocument().putProperty("name", "Text Field");
        textArea = new JTextArea();
        textArea.getDocument().addDocumentListener(new MyDocumentListener());
        textArea.getDocument().putProperty("name", "Text Area");
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(200, 75));
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        JScrollPane displayScrollPane = new JScrollPane(displayArea);
        displayScrollPane.setPreferredSize(new Dimension(200, 75));
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 1.0;
        c.fill = GridBagConstraints.HORIZONTAL;
        gridbag.setConstraints(textField, c);
        add(textField);
        c.gridx = 0;
        c.gridy = 1;
        c.weightx = 0.0;
        c.gridheight = 2;
        c.fill = GridBagConstraints.BOTH;
        gridbag.setConstraints(scrollPane, c);
        add(scrollPane);
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1.0;
        c.weighty = 1.0;
        gridbag.setConstraints(displayScrollPane, c);
        add(displayScrollPane);
        c.gridx = 1;
        c.gridy = 2;
        c.weightx = 0.0;
        c.gridheight = 1;
        c.weighty = 0.0;
        c.fill = GridBagConstraints.HORIZONTAL;
        gridbag.setConstraints(button, c);
        add(button);
        setPreferredSize(new Dimension(450, 250));
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }
    class MyDocumentListener implements DocumentListener {
        final String newline = "\n";
        public void insertUpdate(DocumentEvent e) {
            updateLog(e, "inserted into");
        }
        public void removeUpdate(DocumentEvent e) {
            updateLog(e, "removed from");
        }
        public void changedUpdate(DocumentEvent e) {
            //Plain text components don"t fire these events.
        }
        public void updateLog(DocumentEvent e, String action) {
            Document doc = (Document)e.getDocument();
            int changeLength = e.getLength();
            displayArea.append(
                changeLength + " character"
              + ((changeLength == 1) ? " " : "s ")
              + action + " " + doc.getProperty("name") + "."
              + newline
              + "  Text length = " + doc.getLength() + newline);
            displayArea.setCaretPosition(displayArea.getDocument().getLength());
        }
    }
    class MyTextActionListener implements ActionListener {
        /** Handle the text field Return. */
        public void actionPerformed(ActionEvent e) {
            int selStart = textArea.getSelectionStart();
            int selEnd = textArea.getSelectionEnd();
            textArea.replaceRange(textField.getText(),
                                  selStart, selEnd);
            textField.selectAll();
        }
    }
    /** Handle button click. */
    public void actionPerformed(ActionEvent e) {
        displayArea.setText("");
        textField.requestFocus();
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //Create and set up the window.
        JFrame frame = new JFrame("DocumentEventDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new DocumentEventDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application"s GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}





DocumentFilter that maps lowercase letters to uppercase

  
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class UpcaseFilter extends DocumentFilter {
  public void insertString(DocumentFilter.FilterBypass fb, int offset,
      String text, AttributeSet attr) throws BadLocationException {
    fb.insertString(offset, text.toUpperCase(), attr);
  }
  //no need to override remove(): inherited version allows all removals
  public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
      String text, AttributeSet attr) throws BadLocationException {
    fb.replace(offset, length, text.toUpperCase(), attr);
  }
  public static void main(String[] args) {
    DocumentFilter dfilter = new UpcaseFilter();
    JTextArea jta = new JTextArea();
    JTextField jtf = new JTextField();
    ((AbstractDocument) jta.getDocument()).setDocumentFilter(dfilter);
    ((AbstractDocument) jtf.getDocument()).setDocumentFilter(dfilter);
    JFrame frame = new JFrame("UpcaseFilter");
    frame.getContentPane().add(jta, java.awt.BorderLayout.CENTER);
    frame.getContentPane().add(jtf, java.awt.BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 120);
    frame.setVisible(true);
  }
}





DocumentListener Demo

  
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.Element;
public class ListenerSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Offset Example");
    Container content = frame.getContentPane();
    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    final Document document = textArea.getDocument();
    document.addDocumentListener(new MyListener());
    content.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}
class MyListener implements DocumentListener {
  public void changedUpdate(DocumentEvent documentEvent) {
    printInfo(documentEvent);
  }
  public void insertUpdate(DocumentEvent documentEvent) {
    printInfo(documentEvent);
  }
  public void removeUpdate(DocumentEvent documentEvent) {
    printInfo(documentEvent);
  }
  public void printInfo(DocumentEvent documentEvent) {
    System.out.println("Offset: " + documentEvent.getOffset());
    System.out.println("Length: " + documentEvent.getLength());
    DocumentEvent.EventType type = documentEvent.getType();
    String typeString = null;
    if (type.equals(DocumentEvent.EventType.CHANGE)) {
      typeString = "Change";
    } else if (type.equals(DocumentEvent.EventType.INSERT)) {
      typeString = "Insert";
    } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
      typeString = "Remove";
    }
    System.out.println("Type  : " + typeString);
    Document documentSource = documentEvent.getDocument();
    Element rootElement = documentSource.getDefaultRootElement();
    DocumentEvent.ElementChange change = documentEvent
        .getChange(rootElement);
    System.out.println("Change: " + change);
  }
};





extends PlainDocument

  
/*
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/**
 * Helper class. Only allows an Double value in the document.
 *
 * @author 
 * @version $Id: DoubleDocument.java 504084 2007-02-06 11:24:46Z dvholten $
 */
public class DoubleDocument extends PlainDocument {
    /**
     * Strip all non digit characters.  The first character must be "-" or "+".
     * Only one "." is allowed.
     */
    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {
        if (str == null) {
            return;
        }
        // Get current value
        String curVal = getText(0, getLength());
        boolean hasDot = curVal.indexOf(".") != -1;
        // Strip non digit characters
        char[] buffer = str.toCharArray();
        char[] digit = new char[buffer.length];
        int j = 0;
        if(offs==0 && buffer!=null && buffer.length>0 && buffer[0]=="-")
            digit[j++] = buffer[0];
        for (int i = 0; i < buffer.length; i++) {
            if(Character.isDigit(buffer[i]))
                digit[j++] = buffer[i];
            if(!hasDot && buffer[i]=="."){
                digit[j++] = ".";
                hasDot = true;
            }
        }
        // Now, test that new value is within range.
        String added = new String(digit, 0, j);
        try{
            StringBuffer val = new StringBuffer(curVal);
            val.insert(offs, added);
            String valStr = val.toString();
            if( valStr.equals(".") || valStr.equals("-") || valStr.equals("-."))
                super.insertString(offs, added, a);
            else{
                Double.valueOf( valStr );
                super.insertString(offs, added, a);
            }
        }catch(NumberFormatException e){
            // Ignore insertion, as it results in an out of range value
        }
    }
    public void setValue(double d){
        try{
            remove(0, getLength());
            insertString(0, String.valueOf( d ), null);
        }catch(BadLocationException e){
            // Will not happen because we are sure
            // we use the proper range
        }
    }
    public double getValue(){
        try{
            String t = getText(0, getLength());
            if(t != null && t.length() > 0){
                return Double.parseDouble(t);
            }
            else{
                return 0;
            }
        }catch(BadLocationException e){
            // Will not happen because we are sure
            // we use the proper range
            throw new Error( e.getMessage() );
        }
    }
}





extends PlainDocument to create a float value type text field

   
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 FLOAT = "0123456789.";
  protected String acceptedChars = null;
  protected boolean negativeAccepted = false;
  public JTextFieldFilter() {
    this(FLOAT);
  }
  public JTextFieldFilter(String acceptedchars) {
    acceptedChars = acceptedchars;
  }
  public void setNegativeAccepted(boolean negativeaccepted) {
    if (acceptedChars.equals(FLOAT)) {
      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 (acceptedChars.equals(FLOAT) || (acceptedChars.equals(FLOAT + "-") && negativeAccepted)) {
      if (str.indexOf(".") != -1) {
        if (getText(0, getLength()).indexOf(".") != -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 tf1b;
    JLabel l1b;
    setLayout(new FlowLayout());
    l1b = new JLabel("only float");
    tf1b = new JTextField(10);
    getContentPane().add(l1b);
    getContentPane().add(tf1b);
    tf1b.setDocument(new JTextFieldFilter(JTextFieldFilter.FLOAT));
    setSize(300, 300);
    setVisible(true);
  }
}





extends PlainDocument to create alpha and numeric value based field field

   
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 ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  public static final String NUMERIC = "0123456789";
  public static final String ALPHA_NUMERIC = ALPHA + NUMERIC;
  protected String acceptedChars = null;
  protected boolean negativeAccepted = false;
  public JTextFieldFilter() {
    this(ALPHA_NUMERIC);
  }
  public JTextFieldFilter(String acceptedchars) {
    acceptedChars = acceptedchars;
  }
  public void setNegativeAccepted(boolean negativeaccepted) {
    if (acceptedChars.equals(ALPHA_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) {
      if (str.indexOf(".") != -1) {
        if (getText(0, getLength()).indexOf(".") != -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 tf1c;
    JLabel l1c;
    setLayout(new FlowLayout());
    l1c = new JLabel("only float(can be negative)");
    tf1c = new JTextField(10);
    getContentPane().add(l1c);
    getContentPane().add(tf1c);
    JTextFieldFilter jtff = new JTextFieldFilter(JTextFieldFilter.ALPHA_NUMERIC);
    jtff.setNegativeAccepted(true);
    tf1c.setDocument(jtff);
    
    setSize(300,300);
    setVisible(true);
  }
}





Format JTextField"s text to uppercase

   
 
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(200, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.LEFT));
    DocumentFilter filter = new UppercaseDocumentFilter();
    JTextField firstName = new JTextField();
    firstName.setPreferredSize(new Dimension(100, 20));
    ((AbstractDocument) firstName.getDocument()).setDocumentFilter(filter);
    JTextField lastName = new JTextField();
    lastName.setPreferredSize(new Dimension(100, 20));
    ((AbstractDocument) lastName.getDocument()).setDocumentFilter(filter);
    add(firstName);
    add(lastName);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}
class UppercaseDocumentFilter extends DocumentFilter {
  public void insertString(DocumentFilter.FilterBypass fb, int offset, String text,
      AttributeSet attr) throws BadLocationException {
    fb.insertString(offset, text.toUpperCase(), attr);
  }
  public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,
      AttributeSet attrs) throws BadLocationException {
    fb.replace(offset, length, text.toUpperCase(), attrs);
  }
}





HTMLDocument: Document Iterator Example

  
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.text.AttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class DocumentIteratorExample {
  public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.jexp.ru");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);
    for (HTMLDocument.Iterator iterator = htmlDoc.getIterator(HTML.Tag.A); iterator
        .isValid(); iterator.next()) {
      AttributeSet attributes = iterator.getAttributes();
      String srcString = (String) attributes
          .getAttribute(HTML.Attribute.HREF);
      System.out.print(srcString);
      int startOffset = iterator.getStartOffset();
      int endOffset = iterator.getEndOffset();
      int length = endOffset - startOffset;
      String text = htmlDoc.getText(startOffset, length);
      System.out.println(" - " + text);
    }
    System.exit(0);
  }
}





Implement a document cleaner that maps lowercase letters to uppercase

   

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class UpcaseFilter extends DocumentFilter {
  public void insertString(DocumentFilter.FilterBypass fb, int offset, String text,
      AttributeSet attr) throws BadLocationException {
    fb.insertString(offset, text.toUpperCase(), attr);
  }
  public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,
      AttributeSet attr) throws BadLocationException {
    fb.replace(offset, length, text.toUpperCase(), attr);
  }
  public static void main(String[] args) {
    DocumentFilter dfilter = new UpcaseFilter();
    JTextArea jta = new JTextArea();
    JTextField jtf = new JTextField();
    ((AbstractDocument) jta.getDocument()).setDocumentFilter(dfilter);
    ((AbstractDocument) jtf.getDocument()).setDocumentFilter(dfilter);
    JFrame frame = new JFrame("UpcaseFilter");
    frame.getContentPane().add(jta, java.awt.BorderLayout.CENTER);
    frame.getContentPane().add(jtf, java.awt.BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 120);
    frame.setVisible(true);
  }
}





Override $ key

   
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField(10);

    component.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("typed $"), "actionName");
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}





Overriding - key

   
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField(10);
    component.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("typed -"), "actionName");
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}





Overriding space key

   

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField(10);
    
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(new Character(" "), 0), "actionName");
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}





Prevent the space from being inserted when shift-space is pressed.

   
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField(10);
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(new Character(" "), 0), "none");
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}





React to the document update insert changed event

  
import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DocumentListenerDemo extends JFrame implements DocumentListener {
  private JTextField hourField = new JTextField("12", 3);
  private JTextField minuteField = new JTextField("00", 3);
  private JLabel label = new JLabel();
  public DocumentListenerDemo() {
    setTitle("TextTest");
    setSize(500, 200);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    Container contentPane = getContentPane();
    JPanel p = new JPanel();
    p.add(hourField);
    hourField.getDocument().addDocumentListener(this);
    p.add(minuteField);
    minuteField.getDocument().addDocumentListener(this);
    contentPane.add(p, "Center");
    contentPane.add(label, "North");
  }
  public void insertUpdate(DocumentEvent e) {
    label.setText(e.toString());
  }
  public void removeUpdate(DocumentEvent e) {
    label.setText(e.toString());
  }
  public void changedUpdate(DocumentEvent e) {
  }
  public static void main(String[] args) {
    JFrame frame = new DocumentListenerDemo();
    frame.show();
  }
}





Subclass InputVerifier

   
 
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] args) {
    JTextField tf = new JTextField("");
    tf.setInputVerifier(new MyInputVerifier());
  }
}
class MyInputVerifier extends InputVerifier {
  public boolean verify(JComponent input) {
    JTextField tf = (JTextField) input;
    String pass = tf.getText();
    return pass.equals("AA");
  }
}





This Document restricts the size of the contained plain text to the given number of characters.

  
 
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 * 
 * ---------------------------
 * LengthLimitingDocument.java
 * ---------------------------
 * (C)opyright 2003, 2004, by Thomas Morgner and Contributors.
 *
 * Original Author:  Thomas Morgner;
 * Contributor(s):   David Gilbert (for Object Refinery Limited);
 *
 * $Id: LengthLimitingDocument.java,v 1.3 2005/10/18 13:18:34 mungady Exp $
 *
 * Changes
 * -------
 * 22-Jan-2003 : Initial version
 * 05-Feb-2003 : Documentation
 * 
 */

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/**
 * This Document restricts the size of the contained plain text to the given number of
 * characters.
 *
 * @author Thomas Morgner
 */
public class LengthLimitingDocument extends PlainDocument {
    /** The maximum length. */
    private int maxlen;
    /**
     * Creates a new LengthLimitingDocument, with no limitation.
     */
    public LengthLimitingDocument() {
        this(-1);
    }
    /**
     * Creates a new LengthLimitingDocument with the given limitation. No more than
     * maxlen characters can be added to the document. If maxlen is negative, then
     * no length check is performed.
     *
     * @param maxlen the maximum number of elements in this document
     */
    public LengthLimitingDocument(final int maxlen) {
        super();
        this.maxlen = maxlen;
    }
    /**
     * Sets the maximum number of characters for this document. Existing characters
     * are not removed.
     *
     * @param maxlen the maximum number of characters in this document.
     */
    public void setMaxLength(final int maxlen) {
        this.maxlen = maxlen;
    }
    /**
     * Returns the defined maximum number characters for this document.
     * @return the maximum number of characters
     */
    public int getMaxLength() {
        return this.maxlen;
    }
    /**
     * Inserts the string into the document. If the length of the document would
     * violate the maximum characters restriction, then the string is cut down so
     * that
     * @param offs the offset, where the string should be inserted into the document
     * @param str the string that should be inserted
     * @param a the attribute set assigned for the document
     * @throws javax.swing.text.BadLocationException if the offset is not correct
     */
    public void insertString(final int offs, final String str, final AttributeSet a)
        throws BadLocationException {
        if (str == null) {
            return;
        }
        if (this.maxlen < 0) {
            super.insertString(offs, str, a);
        }
        final char[] numeric = str.toCharArray();
        final StringBuffer b = new StringBuffer();
        b.append(numeric, 0, Math.min(this.maxlen, numeric.length));
        super.insertString(offs, b.toString(), a);
    }
    
}