Java GUI Mad God Talking Series Video Summary (2)

Panel Panel, monitor events (about closing) and button Button

One, Panel and listening events about closing

//这是我自己的包
package GUI;
//导入必要的包
import java.awt.*;
import java.awt.event.*;
public class TestDemo  {
    
    
	public static void main(String[] args) {
    
    
		
		//新建一个窗口对象
		Frame frame = new Frame();
		
		//设置布局 null的意思是清空布局管理器
		frame.setLayout(null);

		//新建一个面板对象  面板可以放到窗口上
		Panel panel = new Panel();
		
		//设置面板的大小及位置  相对于你放的窗口来说
		panel.setBounds(100, 100, 100, 100);
		
		//设置面板背景颜色
		panel.setBackground(Color.YELLOW);
		
		//设置窗口大小 及位置
		frame.setBounds(500, 500, 300, 300);
		
		//设置窗口背景颜色
		frame.setBackground(Color.CYAN);
		
		//将面板放到窗口上
		frame.add(panel);
		
		//设置可见性
		frame.setVisible(true);
		
		//设置监听事件  WindowAdapter是一个类
		frame.addWindowListener(new WindowAdapter(){
    
    
			
			//重写抽象方法
			public void windowClosing(WindowEvent e){
    
    
			  
			  //关闭窗口,关闭程序
			  System.exit(0);
			  
		  }
		});//这样之后点击X(关闭),窗口就会关闭
	}
}

Insert picture description here

Second, the use of Button

The code is as follows (example):

//这是我自己的包
package GUI;
//导入必要的包
import java.awt.*;
import java.awt.event.*;
public class TestDemo  {
    
    
	public static void main(String[] args) {
    
    
		
		Frame frame = new Frame();
		
		//新建很多很多按钮
		Button b1 = new Button("按钮1");
		Button b2 = new Button("按钮2");
		Button b3 = new Button("按钮3");
		Button b4 = new Button("按钮4");
		Button b5 = new Button("按钮5");
		Button b6 = new Button("按钮6");
		
		//把他们添加到frame窗口上面
		frame.add(b1);
		frame.add(b2);
		frame.add(b3);
		frame.add(b4);
		frame.add(b5);
		frame.add(b6);
		
		//设置布局为网格布局,后面两个数字表示2行3列
		frame.setLayout(new GridLayout(2,3));
		frame.setBounds(400, 400, 500, 500);
		frame.setVisible(true);
	}
}

Insert picture description here

to sum up

Familiar with the use of Panel, Button and monitoring events, these are very helpful for later learning! ! ! thanks for watching! ! !

Guess you like

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