文本框的使用(可以在页面交互中直接接收输入内容)


文本框的使用:

1 public TextField num1,num2,num3;
2         num1 = new TextField(10);//表示最多可输入10字节
3         num2 = new TextField(10);
4         num3 = new TextField(20);
 1 public class TestText01 {
 2     public static void main(String[] args)
 3     {
 4         new MyFrame();
 5     }
 6 }
 7 
 8 class MyFrame extends Frame {
 9     public MyFrame() {
10         TextField textField = new TextField();//新建一个文本框
11         add(textField);
12         MyActionListener1 myActionListener = new MyActionListener1();
13         textField.addActionListener(myActionListener);//为文本框增加一个监听器
14         textField.setEchoChar('*');//将所有输入的内容在文本框中显示为*
15         setVisible(true);
16         pack();
17     }
18 }
19 
20 class MyActionListener1 implements ActionListener{//监听器作用:输出文本框中的内容
21     public void actionPerformed(ActionEvent e)
22     {
23         TextField textField = (TextField)e.getSource();
24         System.out.println(textField.getText());
25         textField.setText("");
26     }
27 }

综合实例:

计算器的构建:

 1 public class TestCalc {
 2     public static void main(String[] args)
 3     {
 4         new Calculator().LoadFrame();
 5     }
 6 }
 7 class Calculator extends Frame {
 8     public TextField num1,num2,num3;
 9     public void LoadFrame() {
10         num1 = new TextField(10);
11         num2 = new TextField(10);
12         num3 = new TextField(20);
13         
14         Button button = new Button("=");
15         button.addActionListener(new MyCalculatorListener(this));
16         
17         Label label = new Label("+");
18         setLayout(new FlowLayout());
19         
20         add(num1);
21         add(label);
22         add(num2);
23         add(button);
24         add(num3);
25         
26         pack();
27         setVisible(true);
28         
29         addWindowListener(new WindowAdapter(){
30             public void windowClosing(WindowEvent e) {
31                 System.exit(0);
32             }
33         });
34     }
35 }
36 
37 class MyCalculatorListener implements ActionListener{
38     Calculator calculator = null;
39     
40     public MyCalculatorListener(Calculator calculator)
41     {
42         this.calculator = calculator;
43     }
44     
45     public void actionPerformed(ActionEvent e)
46     {
47         //1.获得被加数和加数
48         Integer n1 = Integer.parseInt(calculator.num1.getText());
49         Integer n2 = Integer.parseInt(calculator.num2.getText());
50         //2.将这个值相加放到第三个框
51         Integer n3 = n1 + n2;
52         calculator.num3.setText(n3.toString());
53         //3.清空前两个数
54         calculator.num1.setText("");
55         calculator.num2.setText("");
56     }
57 }

相关