一、JDialog
JDialog是Swing另一个顶级窗口,
JDialog对话框可分为两种:模态对话框和非模态对话框,所谓模态对话框是指用户需要等到处理完对话框后才能和其他窗口继续交流,而非模态对话框允许用户在处理对话框的同时与其他对话框进行交流,
对话框是模态或非模态可以在创建JDialog对象时为构造方法传入参数而设置,也可以创建之后通过他的setModal()方法来进行设置,JDialog常见方法如下
JDialog(Frame owner) 用来创建一个非模态的对话框,owner为对话框所有者
JDialog(Frame owner,String title) 创建一个具有特定标题的非模态对话框
JDialog(Frame owner,boolean modal) 创建一个指定模式的无标题对话框
二、实例
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JDialogDemo{
public static void main(String[] args)throws Exception{
JButton but1=new JButton("模态对话框");
JButton but2=new JButton("非模态对话框");
JFrame f =new JFrame("JDialog");
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,"JDialog");
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();
}
});
}
}