JFrame和JDialog的简单实现

本文介绍了Java Swing中的JFrame和JDialog组件,讲解了它们的基本使用方法和区别。通过实例展示了如何创建和配置窗口,以及如何将JDialog作为对话框弹出,为Java GUI开发提供基础指南。

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

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

//顶级容器JFrame的实例化
public class container extends JFrame implements ActionListener {
    JButton _model =new JButton("OPEN MODEL DIALOG");
    JButton _nomodel =new JButton("CLOSE MODEL DIALOG");
    JPanel _top=new JPanel();//实例化中间窗体 JPanel
    public container()
    {
        super("JFrame TEST");
        init();
    }
    public void init()
    {
        setSize(480,320);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);//定义窗口关闭按键设置
        setLayout(new BorderLayout());//定义布局
        _model.addActionListener(this);
        _nomodel.addActionListener(this);
        _top.add(_model);
        _top.add(_nomodel);
        add(_top,BorderLayout.NORTH);
        setVisible(true);
    }
    //关联事件源
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource().equals(_model)){
            new MyDialog(this,true,"Model Didlog");
        }
        if(e.getSource().equals(_nomodel)){
            new MyDialog(this,true,"Nomodel Didlog");
        }
    }
    public static void main(String args[])
    {
        container window =new container();
    }
}
//实例化JDialog
class MyDialog extends JDialog implements ActionListener{
    private JButton _ok =new JButton("YES");//定义按键文本
    public MyDialog(JFrame x, boolean modal, String title)
    {
        super(x,title,modal);
        init();
    }
    void init()
    {
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);//关闭时隐藏窗口
        setSize(300,200);
        setLocationRelativeTo(null);
        _ok.addActionListener(this);
        add(_ok, BorderLayout.SOUTH);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {
        dispose();//关闭窗体并释放资源
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值