今天学到java中的GUI这一章节,花了两个小时做出了第一个图形化界面程序,一个简单的加法计算器:
1.源码如下:
- import java.awt.*;
- import java.awt.event.*;
- public class DemoGUI
- {
- public static TextField tf1,tf2,tf3;
- public static void main(String[] args)
- {
- tf1 = new TextField(20);
- tf2 = new TextField(20);
- tf3 = new TextField(20);
- Button bn = new Button("=");
- Label Lb = new Label("+");
- Frame f = new Frame("Mr.Wu的两文本框相加示例");
- f.setLayout(new FlowLayout());
- f.add(tf1);
- f.add(Lb);
- f.add(tf2);
- f.add(bn);
- f.add(tf3);
-
- bn.addActionListener(new MyMonitor());
- f.pack();
- f.setVisible(true);
- }
- }
- class MyMonitor implements ActionListener
- {
- @Override
- public void actionPerformed(ActionEvent e)
- {
- String str1 = DemoGUI.tf1.getText();
- String str2 = DemoGUI.tf2.getText();
- int num1 = Integer.parseInt(str1);
- int num2 = Integer.parseInt(str2);
- int num3 = num1 + num2;
- DemoGUI.tf3.setText(num3+"");
-
- }
- }
复制代码
2.运行效果如下图: |
|