除了可以有多行文本,以及更多的功能之外,JTextArea 与 JTextField 很相似

除了可以有多行文本,以及更多的功能之外,JTextArea 与 JTextField 很相似。它有一个
比较常用的方法 append( );使用它你能很容易地在 JTextArea 里累积大量文本,比起长
期以来在命令行程序中把文本打印到标准输出的做法,这使得 Swing 编程成为了一种进步
(因为可以往回滚动)。作为一个例子,下面的程序使用第 11 章“地名生成器”的输出来填
充 JTextArea。

//: c14:TextArea.java
// Using the JTextArea control.
import javax.swing.*;
import java.awt.event.*; 
import java.awt.*; 
import java.util.*; 
import com.bruceeckel.swing.*; 
import com.bruceeckel.util.*; 


public class TextArea extends JFrame { 
private JButton 
    b = new JButton("Add Data"), 
    c = new JButton("Clear Data"); 
private JTextArea t = new JTextArea(20, 40); 
private Map m = new HashMap();
public TextArea() {
// Use up all the data:
    Collections2.fill(m, Collections2.geography, 
      CountryCapitals.pairs.length); 
    b.addActionListener(new ActionListener() { 
public void actionPerformed(ActionEvent e) { 
        Iterator it = m.entrySet().iterator(); 
while(it.hasNext()) { 
          Map.Entry me = (Map.Entry)(it.next()); 
          t.append(me.getKey() + ": "+ me.getValue()+"\n");
        }
      }
    });
    c.addActionListener(new ActionListener() { 
public void actionPerformed(ActionEvent e) { 
        t.setText("");
      }
    });
    Container cp = getContentPane(); 
    cp.setLayout(new FlowLayout()); 
    cp.add(new JScrollPane(t)); 
    cp.add(b);
    cp.add(c);
  }
public static void main(String[] args) { 
    Console.run(new TextArea(), 475, 425); 
  }
} ///:~


这里使用了JFrame而不是JApplet,因为它要从本地磁盘中读取数据,因此不能作为applet
在HTML网页里运行。


在init( )方法中,用国家及其首都名称来填充Map。注意,对于其中的两个按钮,因为在程
序中你不再需要引用监听器,所以直接创建ActionListener对象并向按钮注册,而没有定
义中间变量。“Add Data”按钮格式化并且添加所有数据,“Clear Data”按钮使用setText( )
方法来清除JtextArea中的所有文本。


在JTextArea被加入到applet的之前,先被包装进了JscrollPane,它被用来在屏幕上的文
本太多的时候进行滚动控制。这么做就足以得到完整的滚动功能。由于我曾试图在其它GUI
编程环境中得到类似功能,所以我对像JScrollPane这样设计良好﹑使用简单的组件印象非

常深刻。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值