Swing
1、简介
Swing并没有完全取代AWT,而是基于AWT的架构之上。Swing仅仅是提供了能力更强大的用户界面组件。在使用Swing编写的程序中,还需要使用基本的AWT处理事件。从现在开始,Swing是“被绘制的”用户界面 ;AWT是指像事件处理这样的窗口工具箱的底层机制。
2、窗口和面板
import javax.swing.*;
import java.awt.*;
public class JFrameDemo {
//初始化窗口
public static void init() {
JFrame jFrame = new JFrame("Jframe窗口");
jFrame.setBounds(100,100,500,500);
jFrame.setBackground(Color.white);
jFrame.setResizable(true);
jFrame.setVisible(true);
jFrame.setLayout(new FlowLayout());
JLabel jLabel = new JLabel("Jframe 文字标签");
jFrame.add(jLabel,BorderLayout.CENTER);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
init();
}
}
执行结果:
2、弹窗
弹出的窗口,默认有关闭事件
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* 主窗口
*/
public class DialogDemo extends JFrame{
public DialogDemo() {
//设置窗口属性
this.setBounds(100,100,500,500);
this.setBackground(Color.BLACK);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//用容器装组件
Container container = this.getContentPane();
container.setLayout(new FlowLayout());
Button button = new Button("button");
button.setBounds(100,100,200,100);
container.add(button);
//给按钮添加事件监听
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
});
}
public static void main(String[] args) {
new DialogDemo();
}
}
/**
* 弹出的窗口
*/
class MyDialog extends JDialog{
public MyDialog() {
this.setBounds(100,100,200,200);
this.setVisible(true);
this.setResizable(false);
this.setBackground(Color.green);
//用一个容器来装标签
Container container = this.getContentPane();
container.setLayout(new FlowLayout());
container.add(new JLabel("Jlabel 标签"));
}
}
3、标签和图标
绘出自己的图标
import javax.swing.*;
import java.awt.*;
/**
* Icon图标,继承Jframe的同时实现Icon接口
*/
public class IconlDemo extends JFrame implements Icon {