Dialog(模态和非模态两种,FileDialog不再举例):
package gui.test08;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestDialog extends Frame {
private TextField tf = new TextField(10);
public TestDialog() {
Button b1 = new Button("打开模态对话框");
Button b2 = new Button("打开非模态对话框");
add(tf,"North");
add(b1,"Center");
add(b2,BorderLayout.EAST);
//
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MyDialog dlg = new MyDialog(TestDialog.this,"modal dialog",true);
dlg.setInfo(tf.getText());
dlg.setVisible(true);//模态对话框阻塞在这里,直到它被关闭
//...
tf.setText(dlg.getInfo());
}
});
//
//
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MyDialog dlg = new MyDialog(TestDialog.this,"nonModal dialog",false);
dlg.setInfo(tf.getText());
dlg.setVisible(true);//非模态对话框后面的代码会继续往下执行,不会阻塞
//...
//tf.setText(dlg.getInfo());
}
});
//
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
public static void main(String[] args) {
TestDialog mainFrame = new TestDialog();
mainFrame.setSize(400, 400);
mainFrame.setTitle("TestDialog");
mainFrame.setVisible(true);
}
public void setInfo(String text) {
tf.setText(text);
}
}
///
package gui.test08;
import java.awt.Button;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyDialog extends Dialog {
private TextField tf = new TextField(10);
private String strInfo = null;
public MyDialog(Frame testDialog, String title, boolean modal) {
super(testDialog, title, modal);
setBounds(0, 0, 200, 150);
Button b1 = new Button("应用");
Button b2 = new Button("确定");
//
add(tf, "North");
add(b1, "Center");
add(b2, "East");
if (this.isModal()) {
b1.setEnabled(false);
}
//
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
((TestDialog)(MyDialog.this.getOwner())).setInfo(tf.getText());
}
});
//
//
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(isModal()){
strInfo = tf.getText();
}else{
((TestDialog)(MyDialog.this.getParent())).setInfo(tf.getText());
}
dispose();
}
});
//
}
public String getInfo() {
return strInfo;
}
public void setInfo(String text) {
tf.setText(text);
}
}