Dialog是Window类的子类,是一个容器属于特殊组件。对话框是可以独立存在的顶级窗口,用法与普通窗口类似,但要注意以下两点:
1.对话框通常依赖于其他窗口,就是一个parent窗口。
2.对话框有非模式(non-modal)和模式(modal)两种。
Dialog有多个重载构造器,有3个参数:
1.owner: 指定以来的窗口。
2.title: 对话框的标题。
3.modal:对话框的模式。
package javaAWT;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogTest {
Frame frame = new Frame("对话框");
Dialog d1 = new Dialog(frame, "模式对话框", true);
Dialog d2 = new Dialog(frame, "非模式对话框", false);
Button b1 = new Button("打开模式对话框");
Button b2 = new Button("打开没模式对话框");
public void init() {
d1.setBounds(, , , );
d2.setBounds(, , , );
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
d1.setVisible(true);
}
});
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
d2.setVisible(true);
}
});
frame.add(b1);
frame.add(b2, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new DialogTest().init();
}
}
FileDialog构造器有3个参数:
parent:依赖窗口
title: 标题
mode: FileDialog.LOAD, FileDialog.SAVE
getDirectory(): 获取FileDialog被打开/保存的文件的绝对路径。
getFile():获取FileDialog被打开/保存的文件名。
package javaAWT;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FileDialogTest {
Frame frame = new Frame("文件对话框");
FileDialog fd1 = new FileDialog(frame, "选择打开的文件", FileDialog.LOAD);
FileDialog fd2 = new FileDialog(frame, "选择保存的路径", FileDialog.SAVE);
Button b1 = new Button("打开文件");
Button b2 = new Button("保存文件");
public void init() {
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
fd1.setVisible(true);
System.out.println(fd1.getDirectory() + fd1.getFile());
}
});
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
fd2.setVisible(true);
System.out.println(fd2.getDirectory()+fd2.getFile());
}
});
frame.add(b1);
frame.add(b2, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main() {
new FileDialogTest().init();
}
}