java 24


需求: 把文本框中的数据,通过点击按钮,转移到文本域中。
    同时清空文本框中的数据

代码:(步骤都注释了)

 1 public class FrameDemo4 {
 2 
 3     public static void main(String[] args) {
 4 
 5         // 创建窗体对象
 6         Frame f = new Frame("数据转移");
 7         // 设置窗体属性
 8         f.setBounds(300, 300, 300, 300);
 9         // 设置窗体的布局为流水布局
10         f.setLayout(new FlowLayout());
11 
12         // 创建文本框
13         final TextField tf = new TextField(30);
14         // 创建按钮
15         Button b = new Button("转移");
16         // 设置按钮的大小
17         //b.setSize(20, 20);
18         // 创建文本域
19         final TextArea ta = new TextArea(14, 35);
20 
21         // 把上面的组件添加到窗体中,注意先后顺序
22         f.add(tf);
23         f.add(b);
24         f.add(ta);
25 
26         // 对窗口设置关闭监听
27         f.addWindowListener(new WindowAdapter() {
28             public void windowClosing(WindowEvent e) {
29                 System.exit(0);
30             }
31         });
32         // 对按钮添加事件(转移文本框中的数据到文本域中,并清空数据)
33         b.addActionListener(new ActionListener() {
34 
35             public void actionPerformed(ActionEvent e) {
36                 // 获取文本框中的数据
37                 String str = tf.getText().trim();
38                 // 清空文本框中的数据(输入空格替换掉以前的数据)
39                 tf.setText(" ");
40 
41                 // 把获取到的文本框的数据添加到文本域中
42                 // 并且为了防止后面的数据覆盖掉前面的数据,这里使用追加方法
43                 ta.append(str + "
");
44 
45                 // 美观,添加光标
46                 tf.requestFocus();
47             }
48         });
49         // 使窗体显示
50         f.setVisible(true);
51     }
52 
53 }
何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5956581.html