Java之GUI 狂神说系列总结(4)

在此感谢Java狂神说!!!

一、按钮和窗口的监听事件

//这是我自己的包
package GUI;
//导入必要的包
import java.awt.*;
import java.awt.event.*;
public class TestDemo  {
    
    
	public static void main(String[] args) {
    
    
		
		//新建一个frame 和一个button
		Frame frame = new Frame();
		Button button = new Button("别点我");
		
		//新建一个MyActionListener类
		MyActionListener1 myActionListener = new MyActionListener1();
		
		//添加按钮监听事件
		button.addActionListener(myActionListener);
		
		//添加窗口关闭事件
		windowClose(frame);
		
		//将按钮添加到frame上
		frame.add(button);
		
		//设置大小 及可见
		frame.setBounds(100,100,200,200);
		frame.setVisible(true);
		}
		//实现关闭窗口的方法
	 static  void  windowClose(Frame frame){
    
    
		frame.addWindowListener(new WindowAdapter(){
    
    
			public void windowClosing(WindowEvent e){
    
    
				System.exit(0);
		}
		});
		
	}
}
//按钮监听事件类 ActionListener是一个接口
class MyActionListener1 implements ActionListener{
    
    
	
	//实现其中的抽象方法,触发时会执行此方法
	public void actionPerformed(ActionEvent e){
    
    
		
		//输出这句话
		System.out.println("您点击了按钮!");
	}
}

在这里插入图片描述

二.两个按钮可以共用一个监听

//这是我自己的包
package GUI;
//导入必要的包
import java.awt.*;
import java.awt.event.*;
public class TestDemo  {
    
    
	public static void main(String[] args) {
    
    
		
		//新建一个frame 和一个button
		Frame frame = new Frame();
		frame.setLayout(new GridLayout(2,1));
		Button button = new Button("别点我");
		Button button1 = new Button("点我");
		
		//设置按钮信息
		button.setActionCommand("别点我啊啊啊!");
		
		//新建一个MyActionListener类
		MyActionListener1 myActionListener = new MyActionListener1();
		
		//添加按钮监听事件
		button.addActionListener(myActionListener);
		button1.addActionListener(myActionListener);
		
		//添加窗口关闭事件
		windowClose(frame);
		
		//将按钮添加到frame上
		frame.add(button);
		frame.add(button1);
		
		//设置大小 及可见
		frame.setBounds(100,100,200,200);
		frame.setVisible(true);
		}
		//实现关闭窗口的方法
	 static  void  windowClose(Frame frame){
    
    
		frame.addWindowListener(new WindowAdapter(){
    
    
			public void windowClosing(WindowEvent e){
    
    
				System.exit(0);
		}
		});
		
	}
}
//按钮监听事件类 ActionListener是一个接口
class MyActionListener1 implements ActionListener{
    
    
	
	//实现其中的抽象方法,触发时会执行此方法
	public void actionPerformed(ActionEvent e){
    
    
		
		//输出这句话 获取按钮信息
		System.out.println(""+e.getActionCommand());
	}
}

在这里插入图片描述

猜你喜欢

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