代码如下:
package Swing组件;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class Demo01 extends JDialog {
public Demo01(){
setTitle("对话框");
Container c = getContentPane(); // 获取窗体容器
c.add(new JLabel("这是一个对话框"));
setVisible(true); // 设置窗体可见
setBounds(100,100,100,100); // 设置窗体坐标和大小
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setTitle("大窗口");
f.setBounds(50,50,300,300);
Container c = f.getContentPane();
JButton btn = new JButton("弹出对话框");
c.setLayout( new FlowLayout()); // 设置使用流布局
c.add(btn);
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
btn.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
new Demo01();
}
});
}
}
运行结果:
由图可知,点击弹出对话框,可以弹出无穷多个对话框,若要限制对话框的弹出次数,即阻挡对话框的多次弹出,则需要修改代码。
修改后代码:
package Swing组件;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class Demo01 extends JDialog {
public Demo01(JFrame frame){
/*
第一个参数:父窗体对象
第二个参数:对话框标题
第三个参数:是否阻塞父窗体
*/
super(frame,"对话框标题",true);
Container c = getContentPane(); // 获取窗体容器
c.add(new JLabel("这是一个对话框"));
setBounds(100,100,100,100); // 设置窗体坐标和大小
}
public static void main(String[] args) {
JFrame f = new JFrame("父窗体");
f.setBounds(50,50,300,300);
Container c = f.getContentPane();
JButton btn = new JButton("弹出对话框");
c.setLayout( new FlowLayout()); // 设置使用流布局
c.add(btn);
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
btn.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Demo01 d =new Demo01(f);
d.setVisible(true);
}
});
}
}
运行结果:
只能弹出一个对话框