Java GUI crazy god said series summary (4)

Thanks to the Java crazy god! ! !

One, the button and window monitoring event

//这是我自己的包
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("您点击了按钮!");
	}
}

Insert picture description here

2. Two buttons can share one monitor

//这是我自己的包
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());
	}
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45911278/article/details/111564525