*注: 作者使用的是 jdk1.8.0_121 版本,可根据下方链接进行下载
jdk1.8.0_121 64位
jdk1.8.0_131 32位
1.基础界面
Frame frame = new Frame();
frame.setVisible(true);
2.关闭按钮监听
frame.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
//给frame添加一个窗口监听 WindowListener
frame.addWindowListener();
//窗口监听里面的方法很多,当只取其中一个方法时,需要给监听增加一个适配器 Adapter
frame.addWindowListener(new WindowAdapter() {});
//到适配器中使用方法 windowClosing()
public void windowClosing(WindowEvent e) {}
//添加执行关闭程序 0 是退出码,填写-1也可以
System.exit(0);
2.1. WindowListener 7个方法讲解
//窗口打开时调用
windowOpened()
//窗口被最小化时调用
windowIconified()
//窗口被最小化还原时调用
windowDeiconified()
//窗口失去活性时调用
windowDeactivated()
//窗口正在被关闭时调用
windowClosing()
//窗口被关闭时调用
windowClosed()
//窗口被完全激活时调用
windowActivated()
3.设置窗口大小
frame.seetSize(500, 500); //width, height
4.添加标题
4.1. 声明的时候直接加标题
Frame frame = new Frame("javaGUI界面");
4.2. 调用方法设置标题
frame.setTitle("javaGUI界面");
5.配置窗口出现位置
frame.setLocation(500, 500); // x, y
6.设置图标
frame.setIconImage(new ImageIcon("images\\logo.png").getImage()); // "images\\logo.png" => 图片相对路径
7.窗口页面布局
frame.setLayout(null); //实现控件配置的位置
7.1. 常见的几个布局
7.1.1. FlowLayout 流式布局
7.1.1.1. 居中对齐
frame.setLayout(new FlowLayout());
frame.add(new JButton("按钮1"));
frame.add(new JButton("按钮2"));
frame.add(new JButton("按钮3"));
frame.add(new JButton("按钮4"));
7.1.1.2. 左对齐
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.add(new JButton("按钮1"));
frame.add(new JButton("按钮2"));
frame.add(new JButton("按钮3"));
frame.add(new JButton("按钮4"));
7.1.1.3. 右对齐
frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
frame.add(new JButton("按钮1"));
frame.add(new JButton("按钮2"));
frame.add(new JButton("按钮3"));
frame.add(new JButton("按钮4"));
7.1.2. BorderLayout 边界布局 (默认布局)
frame.setLayout(new BorderLayout());
frame.add(new JButton("按钮1"),BorderLayout.EAST);
frame.add(new JButton("按钮2"),BorderLayout.WEST);
frame.add(new JButton("按钮3"),BorderLayout.SOUTH);
frame.add(new JButton("按钮4"),BorderLayout.NORTH);
frame.add(new JButton("按钮5"),BorderLayout.CENTER);
7.1.3. GridLayout 网格布局
frame.setLayout(new GridLayout(3,2,80,50)); // 行数, 列数, 网格水平间距, 网格垂直间距
frame.add(new JButton("按钮1"));
frame.add(new JButton("按钮2"));
frame.add(new JButton("按钮3"));
frame.add(new JButton("按钮4"));
frame.add(new JButton("按钮5"));
7.1.4. null 空布局(绝对定位)
frame.setLayout(null); //坐标相对于是界面左上角为 (0, 0)
JButton jb1 = new JButton("按钮1");
jb1.setBounds(10,30,100,50); // x, y, width, height => 横坐标,纵坐标,宽,高
frame.add(jb1);
JButton jb2 = new JButton("按钮2");
jb2.setBounds(10,190,100,50);
frame.add(jb2);
JButton jb3 = new JButton("按钮3");
jb3.setBounds(210,190,150,50);
frame.add(jb3);
JButton jb4 = new JButton("按钮4");
jb4.setBounds(210,270,100,150);
frame.add(jb4);
8.设置背景颜色
8.1. 颜色
frame.setBackground(Color.red);
8.2. RGB
frame.setBackground(new Color(255,0,0)); // r, g, b