【Java例题】8.1手工编写加法器的可视化程序


1. 手工编写加法器的可视化程序。 一个Frame窗体容器,布局为null,三个TextField组件,一个Button组件。 Button组件上添加ActionEvent事件监听器ActionListener和 函数actionPerformed, 其中,前两个TextField组件进行输入,第三个TextField组件用于输出, 并完成两个整数的加法运算。 注意:还需要对Frame窗体添加WindowEvent事件监听器WindowAdapter和 函数windowClosing,退出程序。 

package chapter8;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class demo1 {
    public static void main(String[] args) {
        Frame f1=new Frame("加法计算器");
        int f1width=800;
        int f1heigh=600;
        f1.setLayout(null);
        f1.setBounds(0, 0, f1width, f1heigh);
        TextField tf1=new TextField();
        tf1.setBounds(f1width/6-50, f1heigh/3, 100,50);
        TextField tf2=new TextField();
        tf2.setBounds(f1width/6*3-50, f1heigh/3, 100,50);
        TextField tf3=new TextField();
        tf3.setBounds(f1width/6*5-50, f1heigh/3, 100,50);
        Button bt1=new Button("计算");
        bt1.setBounds(f1width/2-50, f1heigh/2+100, 100,100);
        f1.add(tf1);
        f1.add(tf2);
        f1.add(tf3);
        f1.add(bt1);
        f1.setVisible(true);
        MyWindowAdapter mwa=new MyWindowAdapter();
        f1.addWindowListener(mwa);
        MyActionListener mal=new MyActionListener(tf1,tf2,tf3);
        bt1.addActionListener(mal);
    }
    static class MyActionListener implements ActionListener{
        TextField tf1;
        TextField tf2;
        TextField tf3;
        
        MyActionListener(TextField tf1,TextField tf2,TextField tf3){
            this.tf1=tf1;
            this.tf2=tf2;
            this.tf3=tf3;
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            int ans=Integer.parseInt(tf1.getText())+Integer.parseInt(tf2.getText());
            tf3.setText(""+ans);
        }
    }
    static class MyWindowAdapter extends WindowAdapter {
        public void windowClosing(WindowEvent we){
            System.exit(-1);
        }
    }
}
原文地址:https://www.cnblogs.com/LPworld/p/10724123.html