Output text view information from JTextField in Java

Description

The following code shows how to output text view information from JTextField.

Example


/*www.java  2 s  . c o  m*/
import java.io.PrintStream;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.View;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame("Text Field View");
    JTextField tf = new JTextField(32);
    tf.setText("That's one small step for man...");
    f.getContentPane().add(tf);
    f.pack();
    f.setVisible(true);

    ViewDisplayer.displayViews(tf, System.out);
  }
}

class ViewDisplayer {
  public static void displayViews(JTextComponent comp, PrintStream out) {
    View rootView = comp.getUI().getRootView(comp);
    displayView(rootView, 0, comp.getDocument(), out);
  }

  public static void displayView(View view, int indent, Document doc,
      PrintStream out) {
    String name = view.getClass().getName();
    for (int i = 0; i < indent; i++) {
      out.print("\t");
    }

    int start = view.getStartOffset();
    int end = view.getEndOffset();
    out.println(name + "; offsets [" + start + ", " + end + "]");
    int viewCount = view.getViewCount();
    if (viewCount == 0) {
      int length = Math.min(32, end - start);
      try {
        String txt = doc.getText(start, length);
        for (int i = 0; i < indent + 1; i++) {
          out.print("\t");
        }
        out.println("[" + txt + "]");
      } catch (BadLocationException e) {
      }
    } else {
      for (int i = 0; i < viewCount; i++) {
        displayView(view.getView(i), indent + 1, doc, out);
      }
    }
  }
}

The code above generates the following result.

Output text view information from 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