在父窗体中调用对话框
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Demo extends JDialog{
public Demo() {
setBounds(200, 200, 100, 100);

Container c = getContentPane();//创建容器
c.add(new JLabel("我是对话框"));
}

public static void main(String[] args) {
JFrame jf = new JFrame("父窗体");//创建父窗体
jf.setVisible(true);//可见
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
jf.setBounds(200, 200, 300, 200);//设置坐标,大小

Container c = jf.getContentPane();//设置容器
c.setLayout(new FlowLayout());//设置布局,使用流布局
JButton btn = new JButton("弹出对话框");//添加组件,按钮
c.add(btn);//将组件添加到容器中

btn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {//匿名内部类
Demo d = new Demo();
d.setVisible(true);//可见
}
});
}
}
将父窗体阻塞
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyJDialog extends JDialog{
private static final long serialVersionUID = 1L;
public MyJDialog(MyFrame frame) {
super(frame, "Hi", true);//初始化,进行阻塞
setBounds(100, 100, 100, 100);
Container c = getContentPane();
c.add(new JLabel("我是对话框"));
}
}

public class MyFrame extends JFrame{
private static final long serialVersionUID = 1L;

public static void main(String[] args) {
new MyFrame();
}

public MyFrame() {
setVisible(true);
setBounds(200, 200, 300, 200);

Container c = getContentPane();
c.setLayout(new FlowLayout());//设置布局,使用流布局
JButton btn = new JButton("弹出对话框");
c.add(btn);

btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new MyJDialog(MyFrame.this).setVisible(true);//调用对话框,可见

}
});
}
}