day007GUI编程中的监听事件
public static void main(String[] args) {
// 1.上下两行一列 2.套 左中右 顺序布局 3.上中 面板内套两行一列 4.下中内套 两行两列
Frame frame = new Frame("this is my Grid");
frame.setBounds(200,200,400,300);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
//上面板 (borderlayout east center west)
Panel panelUp = new Panel(new BorderLayout());
Panel panelUpCent = new Panel(new GridLayout(2,1));
panelUpCent.add(new Button("1111"));
panelUpCent.add(new Button("2222"));
panelUp.add(new Button("west"), BorderLayout.WEST);
panelUp.add(panelUpCent,BorderLayout.CENTER);
panelUp.add(new Button("east"), BorderLayout.EAST);
// panelUpCent.setSize(200,150);
// panelUp.setVisible(true);
// panelUpCent.setVisible(true);
frame.add(panelUp);
Panel panelDown = new Panel(new BorderLayout());
Panel panelDownCent = new Panel(new GridLayout(2,2));
for(int i = 0;i<4;i++){
panelDownCent.add(new Button("Button"+i));
}
// panelDownCent.setSize(200,150);
panelDown.add(new Button("west2"), BorderLayout.WEST);
panelDown.add(panelDownCent,BorderLayout.CENTER);
panelDown.add(new Button("east2"), BorderLayout.EAST);
// panelDown.setVisible(true);
// panelDownCent.setVisible(true);
frame.add(panelDown);
}
}
listener监听事件
-
鼠标监听事件 extends MouseAdapter 重写用到的 点击 按压 等事件
-
窗口监听事件 extends WindowAdapter 重写用到的关于窗口操作的方法
-
Frame 窗口 Button 按钮 TextFile 文本框 Liable 标签 组件中添加监听
-
eg : new Button().addActionListener(按钮用到的监听事件对象);new TextFile.addActionListener(文本用到的监听事件对象);
-
new Frame().addMouseListener(用到的鼠标监听事件对象)
-
new Frame().addWindowListener(用到的窗口监听事件对象)
内部类直接用可以共享外部类的属性等,精简代码
以下是画点代码案例
package awts.lession002;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* @ Author :wwwzhqwww
* @ Date :Created in 14:55 2021/1/3
* @ Description:两个按钮调同一个监听事件
* @ Modified By:
* @Version: $version$
*/
public class TestActionTwo {
public static void main(String[] args) {
Frame frame = new Frame();
MyListener0 myListener = new MyListener0();
Button b1 = new Button("start");
Button b2 = new Button("end");
// b1.setActionCommand("star-1");//不设置走默认值
b1.addActionListener(myListener);
b2.addActionListener(myListener);
frame.setLayout(new FlowLayout());
frame.add(b1);
frame.add(b2);
frame.setBounds(200,200,400,400);
TextField textField = new TextField();
MyListener1 myListener1 = new MyListener1();
textField.addActionListener(myListener1);//默认按下回车键就会触发此事件
frame.add(textField);
frame.setVisible(true);
closeWin(frame);
}
private static void closeWin(Frame frame){
frame.addWindowListener(new WindowAdapter() {