Java对话框Dialog

Dialog

Dialog 是 Window 类的子类,是 一个容器类,属于特殊组件 。 对话框是可以独立存在的顶级窗口, 因此用法与普通窗口的用法几乎完全一样,但是使用对话框需要注意下面两点:

  • 对话框通常依赖于其他窗口,就是通常需要有一个父窗口;
  • 对话框有非模式(non-modal)和模式(modal)两种,当某个模式对话框被打开后,该模式对话框总是位于它的父窗口之上,在模式对话框被关闭之前,父窗口无法获得焦点。
方法名称 方法功能
Dialog(Frame owner, String title, boolean modal) 创建一个对话框对象:
owner:当前对话框的父窗口
title:当前对话框的标题
modal:当前对话框是否是模式对话框,true/false

案例1:

​ 通过Frame、Button、Dialog实现下图效果:

​	[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QqdhiFAq-1612162298369)(./images/DialogDemo1.jpg)]

演示代码1:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DialogDemo1 {
    
    

    public static void main(String[] args) {
    
    

        Frame frame = new Frame("这里测试Dialog");

        Dialog d1 = new Dialog(frame, "模式对话框", true);
        Dialog d2 = new Dialog(frame, "非模式对话框", false);

        Button b1 = new Button("打开模式对话框");
        Button b2 = new Button("打开非模式对话框");

        //设置对话框的大小和位置
        d1.setBounds(20,30,300,400);
        d2.setBounds(20,30,300,400);

        //给b1和b2绑定监听事件
        b1.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                d1.setVisible(true);
            }
        });
        b2.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                d2.setVisible(true);
            }
        });

        //把按钮添加到frame中
        frame.add(b1);
        frame.add(b2,BorderLayout.SOUTH);

        //设置frame最佳大小并可见
        frame.pack();
        frame.setVisible(true);

    }
}

在这里插入图片描述

在Dialog对话框中,可以根据需求,自定义内容

案例:

​ 点击按钮,弹出一个模式对话框,其内容如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ylilqp9e-1612162298372)(./images/DialogDemo2.jpg)]

演示代码:

public class DialogDemo2 {
    
    

    public static void main(String[] args) {
    
    

        Frame frame = new Frame("这里测试Dialog");

        Dialog d1 = new Dialog(frame, "模式对话框", true);

        //往对话框中添加内容
        Box vBox = Box.createVerticalBox();

        vBox.add(new TextField(15));
        vBox.add(new JButton("确认"));
        d1.add(vBox);

        Button b1 = new Button("打开模式对话框");

        //设置对话框的大小和位置
        d1.setBounds(20,30,200,100);


        //给b1绑定监听事件
        b1.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                d1.setVisible(true);
            }
        });


        //把按钮添加到frame中
        frame.add(b1);

        //设置frame最佳大小并可见
        frame.pack();
        frame.setVisible(true);

    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ruan_luqingnian/article/details/113517391
今日推荐