JavaGUI编程 -- Swing之JFrame窗口和弹窗

本文介绍了Swing库中创建JFrame窗口和JDialog弹窗的基本步骤。通过示例代码展示了如何设置窗口背景、添加组件、设置关闭操作以及响应按钮事件弹出对话框。在JFrame中,组件添加到Container中,并设置了窗口大小和位置。JDialog弹窗则在按钮点击事件中触发,无需额外设置关闭操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }
}

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeJiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值