<span style="font-size:12px;color:#ffffff;background-color: rgb(255, 204, 204);">import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class MyDialog extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
static final int YES = 1,NO = 0,CLOSE = -1;
int message = 10;
JButton yes,no;
public MyDialog(JFrame owner,String title,boolean modal){
super(owner,title,modal);
Container con = getContentPane();
con.setLayout(new FlowLayout());
yes = new JButton("Yse");
yes.addActionListener(this);
no = new JButton("No");
no.addActionListener(this);
con.add(yes);
con.add(no);
setBounds(60,60,100,100);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
message = CLOSE;
setVisible(false);
}
});
}
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;
}
}
public class MyDialogTest extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JTextArea text;
JButton button;
MyDialog dialog;
MyDialogTest(String s) {
super(s);
Container con = getContentPane();
con.setLayout(new FlowLayout());
text = new JTextArea(12,20);
button = new JButton("打开对话框");
button.addActionListener(this);
con.add(button);
con.add(new JScrollPane(text));
dialog = new MyDialog(this,"我有模式",true);
setBounds(60,60,300,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
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按钮");
}else if (dialog.getMessage() == MyDialog.CLOSE) {
text.append("\n你单击了对话框的关闭图标");
}
}
}
public static void main(String args[]) {
new MyDialogTest("带对话框的窗口");
}
}</span>