//TestDialog.java package myprojects.testdialog; import java.awt.*; import java.awt.event.*; class TestDialog extends Frame { private TextField tf=new TextField(10); public TestDialog() { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); Button b1=new Button("打开模态对话框"); Button b2=new Button("打开非模态对话框"); this.add(tf,"North"); this.add(b1,"Center"); this.add(b2,"East"); //add.(tf,"North"); //add.(b1,"Center"); //add.(b2,"East"); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ //经常出现的错误,把参数ActionEvent e 写成 ActionListener e MyDialog dlg=new MyDialog(TestDialog.this,"modal Dialog",true); //注意这里的TestDialog.this dlg.setInfo(tf.getText()); dlg.setVisible(true);//模态对话框未被关闭前,主程序是不会往下执行的 //------------------------------ tf.setText(dlg.getInfo()); } }); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ MyDialog dlg=new MyDialog(TestDialog.this,"modal Dialog",false); //注意这里的TestDialog.this dlg.setInfo(tf.getText()); dlg.setVisible(true);// //tf.setText(dlg.setInfo()); } }); } public void setInfo(String strInfo){ tf.setText(strInfo); } public static void main(String args[]) { System.out.println("Starting TestDialog..."); TestDialog mainFrame = new TestDialog(); mainFrame.setSize(400, 400); mainFrame.setTitle("TestDialog"); mainFrame.setVisible(true); } } //MyDialog.java package myprojects.testdialog; import java.awt.Dialog; import java.awt.*; import java.awt.event.*; public class MyDialog extends Dialog { private TextField tf=new TextField(10); private String strInfo=null; public MyDialog(Frame owner,String title,boolean modal){ super(owner,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()==true){ b1.setEnabled(false); } b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ ((TestDialog)MyDialog.this.getOwner()).setInfo(tf.getText()); //注意MyDialog.this.getOwner()可以省略MyDialog.this.,程序在运行过程中如果在当前内部类对象中找不到该方法,会自动添加MyDialog.this.前缀去查找! } }); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(isModal()==true){ strInfo=new String(tf.getText()); } else{ ((TestDialog)getOwner()).setInfo(tf.getText()); //注意这里getOwner()前面省略了MyDialog.this. } dispose(); } }); } public String getInfo(){ return strInfo; } public void setInfo(String strInfo){ tf.setText(strInfo); } }