import java.awt.event.*;
import java.awt.*;
class MyDialog extends Dialog implements ActionListener{
//定义两个静态常量 YES NO
static final int YES=1,NO=0;
int message =-1;Button yes,no;
//MyDialog中的三个参数:Frame f,f是对话框所依赖的窗体;String s,s是对话框的标题;boolean b设置对话框可见与否
MyDialog(Frame f,String s,boolean b){
super(f,s,b);
yes = new Button("yes");
no = new Button("no");
yes.addActionListener(this);
no.addActionListener(this);
setLayout(new FlowLayout());
add(yes);add(no);
setBounds(60,60,120,120);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
}
});
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==yes){
message=YES;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);
//下面参数this是表示对话框所依赖的窗口的引用 即new Dwindow (s);不过我把this替换成new Dwindow (s)的时候编译通过,但是执行的时候却执行不了,不知道是什么原因造成的
dialog = new MyDialog(this,"我有模式",true);
setBounds(60,60,300,300);
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按钮");
}//如果单击对话框的yes按钮
else if(dialog.getMessage()==MyDialog.NO){
text.append("\n你单击了对话框的no按钮");
}
}
}
}
public class Test51 {
public static void main(String args[]){
new Dwindow("带对话框的窗口");
}
}
阅读(1908) | 评论(0) | 转发(0) |