Element Walker : Document « Swing Event « Java Tutorial






Element Walker
import java.awt.BorderLayout;
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");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

    frame.add(scrollPane, BorderLayout.CENTER);
    frame.add(button, BorderLayout.SOUTH);

    frame.setSize(250, 250);
    frame.setVisible(true);
  }
}








15.12.Document
15.12.1.Custom Document FilterCustom Document Filter
15.12.2.extends PlainDocument to create a float value type text field
15.12.3.extends PlainDocument to create alpha and numeric value based field field
15.12.4.Element WalkerElement Walker
15.12.5.Implement a document cleaner that maps lowercase letters to uppercase
15.12.6.Limit JTextField input to a maximum length