1. Swing之JFrame窗口和弹窗

1.1 JFrame窗口

Swing跟AWT不同的是,Swing需要单独设置一个容器Container。

示例:

package GUI.Swing;

import javax.swing.*;
import java.awt.*;

public class TestJFrame {
    // init():初始化方法
    public void init() {
        JFrame jFrame = new JFrame("这是一个JFrame窗口");//JFrame 顶级窗口
        jFrame.setVisible(true);

//      获得容器 这里需要把东西添加到容器中 这点和AWT不同
        Container container = jFrame.getContentPane();
        container.setBackground(Color.ORANGE);


        jFrame.setBounds(100, 100, 400, 200);

//        设置文字Label
        JLabel jLabel = new JLabel("李旭永远的神!");
        container.add(jLabel);

//        让文本标签居中
        jLabel.setHorizontalAlignment(JLabel.CENTER);

//        关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
//        建立一个窗口
        new TestJFrame().init();
    }
}

运行结果:
在这里插入图片描述


1.2 JDIalog弹窗

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);这是多余的 弹窗默认有关闭动作

示例:

package GUI.Swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// 主窗口
public class TestDialog extends JFrame {
    public TestDialog() throws HeadlessException {
        setVisible(true);
        setBounds(100, 100, 400, 200);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//        关闭事件
//        JFrame放东西,需要一个容器
        Container container = getContentPane();
//        绝对定位 传null就是绝对定位
        container.setLayout(null);
//        按钮
        JButton jButton = new JButton("点击弹出一个对话框");
        jButton.setBounds(100, 50, 200, 50);

//        点击这个按钮的时候 弹出一个对话框
        jButton.addActionListener(new ActionListener() { // 监听器
            @Override
            public void actionPerformed(ActionEvent e) {
//                弹窗
                new MyDialog();
            }
        });

        container.add(jButton);
    }

    public static void main(String[] args) {
        new TestDialog();
    }
}

// 弹窗的窗口
class MyDialog extends JDialog {
    public MyDialog() {
        setVisible(true);
        setBounds(500, 100, 500, 500);
//        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 这是多余的 弹窗默认有关闭动作

        Container container = getContentPane();
        container.setBackground(Color.YELLOW);
    }
}

运行结果:
在这里插入图片描述
会出现一个弹窗
在这里插入图片描述



Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐