Java之GUI 狂神说系列视频总结(6)

在此感谢Java狂神说!!

一、简易加法计算器的实现

//这是我自己的包
package GUI;
//导入必要的包
import java.awt.*;
import java.awt.event.*;
public class TestDemo  {
    
    
	public static void main(String[] args) {
    
    
	 new MyFrame3();
	}
}
class MyFrame3 extends Frame{
    
    
	
	//定义三个文本框
	TextField num1,num2,num3;
	
	//构造器
	public MyFrame3(){
    
    
		
		//给他们实例化 设置长度
		num1 = new TextField(10);
		num2 = new TextField(10);
		num3 = new TextField(20);
		
		//设置标签
		Label label = new Label("+");
		
		//设置按钮
		Button button = new Button("=");
		
		//设置布局 为流式布局
		setLayout(new FlowLayout());
		
		//把组件全放在窗口上
		add(num1);
		add(label);
		add(num2);
		add(button);
		add(num3);
		
		button.addActionListener(new MyActionLiatenerw1(this));
		
		setBounds(100,100,650,150);
		setVisible(true);
	}

}
//实现这个监听
	class MyActionLiatenerw1 implements ActionListener{
    
    
		
		//这是计算器那个类
		private  MyFrame3 myFrame3 = null;
		public MyActionLiatenerw1(MyFrame3 myFrame3){
    
    
			this.myFrame3 = myFrame3;
		}
		
		@Override//监听事件
		public void actionPerformed(ActionEvent e) {
    
    
			// TODO Auto-generated method stub
			
			//得到文本框 1 和 2 的数并进行强制类型转换
			int number1 = Integer.parseInt(myFrame3.num1.getText());
			int number2 = Integer.parseInt(myFrame3.num2.getText());
			
			int number3 = number1 + number2;
			
			//将这个数字给num3
			myFrame3.num3.setText(""+number3);
			
			//将num1 num2置空
			myFrame3.num1.setText("");
			myFrame3.num2.setText("");
		}	
	}
		

二、使用内部类实现简易加法计算器

//这是我自己的包
package GUI;
//导入必要的包
import java.awt.*;
import java.awt.event.*;
public class TestDemo  {
    
    
	public static void main(String[] args) {
    
    
	 new MyFrame3();
	}
}
class MyFrame3 extends Frame{
    
    
	
	//定义三个文本框
	TextField num1,num2,num3;
	
	//构造器
	public MyFrame3(){
    
    
		
		//给他们实例化 设置长度
		num1 = new TextField(10);
		num2 = new TextField(10);
		num3 = new TextField(20);
		
		//设置标签
		Label label = new Label("+");
		
		//设置按钮
		Button button = new Button("=");
		
		//设置布局 为流式布局
		setLayout(new FlowLayout());
		
		//把组件全放在窗口上
		add(num1);
		add(label);
		add(num2);
		add(button);
		add(num3);
		
		button.addActionListener(new MyActionLiatenerw1());
		
		setBounds(100,100,650,150);
		setVisible(true);
	}
class MyActionLiatenerw1 implements ActionListener{
    
    
		
		@Override//监听事件
		public void actionPerformed(ActionEvent e) {
    
    
			// TODO Auto-generated method stub
			
			//得到文本框 1 和 2 的数并进行强制类型转换
			int number1 = Integer.parseInt(num1.getText());
			int number2 = Integer.parseInt(num2.getText());
			
			int number3 = number1 + number2;
			
			//将这个数字给num3
			num3.setText(""+number3);
			
			//将num1 num2置空
			num1.setText("");
			num2.setText("");
		}	
	}
		
}

结果如下:

在这里插入图片描述

总结:

上面两种方法效果是一样的,只不过内部类减少了代码的使用,但是看起来会更复杂。

猜你喜欢

转载自blog.csdn.net/qq_45911278/article/details/111571418