13.6 文本区域

“文本区域”很像文字字段,只是它拥有更多的行以及一些引人注目的更多的功能。另外你能在给定位置对一个文本字段追加、插入或者修改文字。这看起来对文本字段有用的功能相当不错,所以设法发现它设计的特性会产生一些困惑。我们可以认为如果我们处处需要“文本区域”的功能,那么可以简单地使用一个线型文字区域在我们将另外使用文本字段的地方。在Java 1.0版中,当它们不是固定的时候我们也得到了一个文本区域的垂直和水平方向的滚动条。在Java 1.1版中,对高级构造器的修改允许我们选择哪个滚动条是当前的。下面的例子演示的仅仅是在Java1.0版的状况下滚动条一直打开。在下一章里我们将看到一个证明Java 1.1版中的文字区域的例程。

  1. //: TextArea1.java
  2. // Using the text area control
  3. import java.awt.*;
  4. import java.applet.*;
  5. public class TextArea1 extends Applet {
  6. Button b1 = new Button("Text Area 1");
  7. Button b2 = new Button("Text Area 2");
  8. Button b3 = new Button("Replace Text");
  9. Button b4 = new Button("Insert Text");
  10. TextArea t1 = new TextArea("t1", 1, 30);
  11. TextArea t2 = new TextArea("t2", 4, 30);
  12. public void init() {
  13. add(b1);
  14. add(t1);
  15. add(b2);
  16. add(t2);
  17. add(b3);
  18. add(b4);
  19. }
  20. public boolean action (Event evt, Object arg) {
  21. if(evt.target.equals(b1))
  22. getAppletContext().showStatus(t1.getText());
  23. else if(evt.target.equals(b2)) {
  24. t2.setText("Inserted by Button 2");
  25. t2.appendText(": " + t1.getText());
  26. getAppletContext().showStatus(t2.getText());
  27. }
  28. else if(evt.target.equals(b3)) {
  29. String s = " Replacement ";
  30. t2.replaceText(s, 3, 3 + s.length());
  31. }
  32. else if(evt.target.equals(b4))
  33. t2.insertText(" Inserted ", 10);
  34. // Let the base class handle it:
  35. else
  36. return super.action(evt, arg);
  37. return true; // We've handled it here
  38. }
  39. } ///:~

程序中有几个不同的“文本区域”构造器,这其中的一个在此处显示了一个初始字符串和行号和列号。不同的按钮显示得到、追加、修改和插入文字。