日期:2014-05-20  浏览次数:20743 次

java中关于对话框的问题
import java.awt.*;
import java.awt.event.*;

  class Mydialog extends Dialog implements ActionListener
{ static final int YES=1,NO=0;
  int message ;Button yes,no;
  Mydialog(Frame f,String s,boolean b)
  { super(f,s,b);
yes=new Button("Yes");yes.addActionListener(this);  
no=new Button("No");no.addActionListener(this);  

setLayout(new FlowLayout());
add(yes);
add(no);
setBounds(60,60,100,100);
addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
  message=-1;setVisible(false);
  }
  });
  }
public void actionPerformed(ActionEvent e)
 
{ if(e.getSource()==yes)
{ message=YES;
// setVisible(false);
yes.setEnabled(false);
//setVisible(false);
 
}
else if(e.getSource()==no)
{ message=NO;setVisible(false);
 
}  
}
 
public int getMessage()
{ return message;
 
  }
}

class Dwindow extends Frame implements ActionListener
  { TextArea text; Button button;Mydialog dialog;
  Dwindow(String s)
  { super(s);
  text=new TextArea(5,22);button=new Button("打开对话框");  
  button.addActionListener(this);
  setLayout(new FlowLayout());
  add(button);
  add(text);
  dialog=new Mydialog(this,"我有模式",true);
  setBounds(60,60,200,200); 
  setVisible(true); 
  validate();
  addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
  System.exit(0);
  }
  });
   
  }
  public void actionPerformed(ActionEvent e)
 
{ if(e.getSource()==button)  
{ dialog.setVisible(true);
if(dialog.getMessage()==Mydialog.YES)
{ text.append("\n 我单机了对话框yes按钮");
}
else if(dialog.getMessage()==Mydialog.NO)
{ text.append("\n 我单机了对话框no按钮");
}
}
}  
   
  }


public class DialogExa {

/**
* @param args
*/
public static void main(String[] args) {
new Dwindow("dddsfdf");
// TODO Auto-generated method stub

}

}

上面的程序实现点击按钮,弹出对话框,在点击对话框的按钮,把点击的按钮信息在文本框输出。 
 { if(e.getSource()==yes)
{ message=YES;
// setVisible(false);
yes.setEnabled(false);
//setVisible(false);
此处如果启用setVisible(false);不使用setEnabled(false);当点击对话框yes按钮,对话框消失。这儿的消失是对话框不可见,但仍占用内存,可以这样理解吧??


------解决方案--------------------
JDK:
public void setVisible(boolean b)
“如果该参数(b)为 false,则隐藏 Dialog,并且随后导致返回 setVisible(true)(如果它目前受阻塞)。 ”
说得很清楚,仅仅是隐藏。


public void dispose()
“释放由此 Window、其子组件及其拥有的所有子组件所使用的所有本机屏幕资源。即这些 Component 的资源将被破坏,它们使用的所有内存都将返回到操作系统,并将它们标记为不可显示。 ”
所以如果你要释放掉对话框占有的资源,要用dispose()方法。