通过使用 JTextPane 组件,不用费多少工夫,就能支持许多编辑操作。下面的例子是对这
个组件的简单应用,其中忽略了该组件所能提供的其他的大量功能:
//: 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);
}
} ///:~
按钮的功能只是添加一些随机生成的文本。JTextPane的目的是提供即时编辑文本的功能,
所以这里没有append( )方法。在本例中(坦白地说,这不是一个可以发挥JTextPane功
能的好例子),文本必须被捕获并修改,然后使用setText( )将其放回到文本面板中。
如前所述,applet的缺省布局方式是使用BorderLayout。如果你向面板中加入组件的时候
没有指定任何细节,那么它将从中间开始填充面板直到与边框对齐。不过,要是你像本例
中这样指定了一种环绕区域(NORTH, SOUTH, EAST或者WEST),组件将被调整到这
个区域内;这里,按钮将处于屏幕的底部。
个组件的简单应用,其中忽略了该组件所能提供的其他的大量功能:
//: 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);
}
} ///:~
按钮的功能只是添加一些随机生成的文本。JTextPane的目的是提供即时编辑文本的功能,
所以这里没有append( )方法。在本例中(坦白地说,这不是一个可以发挥JTextPane功
能的好例子),文本必须被捕获并修改,然后使用setText( )将其放回到文本面板中。
如前所述,applet的缺省布局方式是使用BorderLayout。如果你向面板中加入组件的时候
没有指定任何细节,那么它将从中间开始填充面板直到与边框对齐。不过,要是你像本例
中这样指定了一种环绕区域(NORTH, SOUTH, EAST或者WEST),组件将被调整到这
个区域内;这里,按钮将处于屏幕的底部。
注意,JTextPane还有诸如自动换行的内置功能。其它的功能你可以参考JDK文档。