Java基础入门 JDialog

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/82354452

JDialog是Swing另一个顶级窗口,它和Dialog一样都有对话框,JDialog对话框可分为两种:模态对话框和非模态对话框,所谓模态对话框是指用户需要等到处理完对话框后才能和其他窗口继续交流,而非模态对话框允许用户在处理对话框的同时与其他对话框进行交流,对话框是模态或非模态可以在创建Dialog对象时为构造方法传入参数而设置,也可以创建之后通过他的setModal()方法来进行设置,JDialog常见方法如下:

JDialog构造方法
方法声明 功能描述
JDialog(Frame owner) 用来创建一个非模态的对话框,owner为对话框所有者
JDialog(Frame owner,String title) 创建一个具有特定标题的非模态对话框
JDialog(Frame owner,boolean modal) 创建一个指定模式的无标题对话框

上面三个构造方法都需要接收一个Frame类型的对象,表示对话框所有者,若该对话框没有所有者则将owner修改为null

下面通过一个案例来学习JDialog对话框:

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

public class Main{
	public static void main(String[] args)throws Exception{
        JButton but1=new JButton("模态对话框");
        JButton but2=new JButton("非模态对话框");
        JFrame f=new JFrame("DialogDemo");
        f.setSize(500, 400);
        f.setLocation(300, 200);
        f.setLayout(new FlowLayout());//设置布局管理器
        f.add(but1);
        f.add(but2);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭按钮
        f.setVisible(true);
        
        final JLabel label=new JLabel();//创建一个标签
        final JDialog dialog=new JDialog(f,"Dialog");
        dialog.setSize(220,150);
        dialog.setLocation(400, 300);
        dialog.setLayout(new FlowLayout());
        final JButton but3=new JButton("确认");
        dialog.add(but3);
        
        //为模态对话框添加点击事件
        but1.addActionListener(new ActionListener(){
        	public void actionPerformed(ActionEvent e){
        		dialog.setModal(true);//设置对话框为模态
        		if(dialog.getComponents().length==1){//若对话框中还没有添加标签则添加上
        			dialog.add(label);
        		}
        		label.setText("模式对话窗,点击确认关闭");//修改标签内容
        		dialog.setVisible(true);
        	}
        });
        
        but2.addActionListener(new ActionListener(){
        	public void actionPerformed(ActionEvent e){
        		dialog.setModal(false);//设置对话框为模态
        		if(dialog.getComponents().length==1){//若对话框中还没有添加标签则添加上
        			dialog.add(label);
        		}
        		label.setText("模式对话窗,点击确认关闭");//修改标签内容
        		dialog.setVisible(true);
        	}
        });
        
        but3.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				dialog.dispose();
			}
		});
	}
}

运行程序后会出现一个窗口,若点击模式对话框后,必须先关闭Dialog才能关闭DialogDemo,而点击非模式对话框后,无论是否关闭Dialog都可以关闭DialogDemo

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/82354452