Java JTextArea get Document Element

Description

Java JTextArea get Document Element

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 Main {
   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());
               System.out.println(element.getName());
               System.out.println(element.getAttributes());
               element = iterator.next();
            }/*from   w  ww  .ja  v a  2  s. co m*/
         }
      };
      button.addActionListener(actionListener);

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

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



PreviousNext

Related