对话框(JDialog)是Swing中的一种顶层容器,它与框架类似都是可以移动窗口。与框架不同的是,对话框一般依附于一个框架之上,由该框架来调用。对话框分为有模式对话框和非模式对话框,有模式对话框是指在该对话框被关闭之前,其它窗口无法接收任何形式的输入,直到对话框被关闭;而非模式对话框允许用户在处理对话框的同时与其它窗口进行交流。
对话框采用JDialog类来实现,其主要构造方法如下:
- JDialog(Frame owner):创建一个没有标题的非模式对话框。
- JDialog(Frame owner, boolean modal):创建一个指定模式的没有标题的对话框,话框架的模式由参数modal来指定,true为有模式对话框,false为非模式对话框。
- JDialog(Frame owner, String title):创建一个有标题的非模式对话框。
- JDialog(Frame owner, String title, boolean modal):创建一个指定模式的有标题的对话框,话框架的模式由参数modal来指定。
与JFrame类似,刚创建的对话框是不可见的,需要调用setVisible(true)方法才能将其显示出来。
【例1】下面程序演示了对话框的创建以及JFrame窗口与对话框之间的通信。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JDialogDemo extends JDialog{
JTextField textField=new JTextField(12);
JTextArea textArea=new JTextArea();
JButton sendButton=new JButton("发送信息");
JButton closeButton=new JButton("关闭对话框");
public JDialogDemo(Frame owner,String title,boolean modal,
JTextArea text) {
super(owner,title,modal);//调用父类的构造方法
setSize(300,200);
setLocationRelativeTo(null);
JPanel panel1=new JPanel();
panel1.add(new JLabel("传递给窗口的信息:"));
panel1.add(textField);
JPanel panel2=new JPanel();
panel2.add(sendButton);
panel2.add(closeButton);
add(panel1,BorderLayout.NORTH);
add(textArea,BorderLayout.CENTER);
add(panel2,BorderLayout.SOUTH);
//发送信息按钮注册事件监听器
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//向传递给对话框的窗口文本区组件添加信息
text.append(textField.getText()+"\n");
}
});
//关闭对话框按钮注册事件监听器
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);//设置对话框为不可视
}
});
}
public static void main(String[] args) {
JFrame frame=new JFrame("主窗口");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JTextField textField=new JTextField(12);
JTextArea textArea=new JTextArea();
JButton showButton=new JButton("显示对话框");
JButton sendButton=new JButton("发送信息");
JDialogDemo dialog=new JDialogDemo(frame,"对话框",false,textArea);
//显示对话框按钮注册事件监听器
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(true);//设置对话框为可视
}
});
//发送信息按钮注册事件监听器
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//向对话框中文本区组件添加信息
dialog.textArea.append(textField.getText()+"\n");
}
});
JPanel panel1=new JPanel();
panel1.add(new JLabel("传递给对话框的信息:"));
panel1.add(textField);
JPanel panel2=new JPanel();
panel2.add(showButton);
panel2.add(sendButton);
frame.add(panel1,BorderLayout