Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in Java
Prev Contents / Index Next

A mini-editor

The JTextPane control provides a great deal of support for editing, without much effort. The following example makes very simple use of this component, ignoring the bulk of the functionality of the class:

//: c14:TextPane.java
// The JTextPane control is a little editor.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;
import com.bruceeckel.util.*;

public class TextPane extends JFrame {
  private JButton b = new JButton("Add Text");
  private JTextPane tp = new JTextPane();
  private static Generator sg =
    new Arrays2.RandStringGenerator(7);
  public TextPane() {
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        for(int i = 1; i < 10; i++)
          tp.setText(tp.getText() + sg.next() + "\n");
      }
    });
    Container cp = getContentPane();
    cp.add(new JScrollPane(tp));
    cp.add(BorderLayout.SOUTH, b);
  }
  public static void main(String[] args) {
    Console.run(new TextPane(), 475, 425);
  }
} ///:~


The button just adds randomly generated text. The intent of the JTextPane is to allow text to be edited in place, so you will see that there is no append( ) method. In this case (admittedly, a poor use of the capabilities of JTextPane), the text must be captured, modified, and placed back into the pane using setText( ).

As mentioned before, the default layout behavior of an applet is to use the BorderLayout. If you add something to the pane without specifying any details, it just fills the center of the pane out to the edges. However, if you specify one of the surrounding regions (NORTH, SOUTH, EAST, or WEST) as is done here, the component will fit itself into that region; in this case, the button will nest down at the bottom of the screen.

Notice the built-in features of JTextPane, such as automatic line wrapping. There are lots of other features that you can look up using the JDK documentation.
Thinking in Java
Prev Contents / Index Next


 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire