以下内容是GUI编程的部分内容,基于对狂神说《GUI编程从入门到游戏实战》的基础编写。
AWT
容器
Frame frame=new Frame();
//设置窗口是否可见,默认为false
frame.setVisible(true);
//设置窗口大小
frame.setSize(x,y);
//设置窗口大小不变,默认为true
frame.setResizable(false);
面板
Panel panel=new Panel();
监听事件,监听窗口关闭事件 System.exit(0)
适配器模式:
frame.addWindowListener(new WindowAdapter(){
//窗口点击关闭的时候需要做的事情
public void windowClosing(WindowEvent e){
//结束程序
System.exit(0);
}
});
事件监听
当某个事情发生的时候,所进行的事情。
package GUI1;
import java.awt.*;
import java.awt.event.*;
public class TestActionEvent {
public static void main(String[] args) {
//按下按钮,触发一些事件
Frame frame=new Frame();
Button button=new Button();
//因为.addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
MyActionListener myActionListener=new MyActionListener();
button.addActionListener(myActionListener);
//可以直接new一个接口 button.addActionListener(new AbstractAction)
frame.add(button,BorderLayout.CENTER);
frame.pack();
windowClose(frame);//关闭窗口
frame.setVisible(true);
}
//关闭窗口的事件
private static void windowClose(Frame frame) {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("成功按下按钮!");
}
}