JDialog弹窗
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//主窗口
public class JDialogDemo extends JFrame {
public JDialogDemo() throws HeadlessException {
this.setBounds(200,200,300,200);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.add(new JLabel("asdfg"));
//JFrame的容器
Container container = this.getContentPane();
//绝对布局
container.setLayout(null);
JButton jButton = new JButton("弹窗");
jButton.setBounds(100,1000,200,50);
//点击按钮弹出一个弹窗
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new MyDialogDemo();
}
});
container.add(jButton);
}
public static void main(String[] args) {
new JDialogDemo();
}
}
//弹窗窗口
class MyDialogDemo extends JDialog{
public MyDialogDemo() {
this.setVisible(true);
this.setBounds(500,500,500,500);
//this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);自带关闭监听
Container container = this.getContentPane();
container.setLayout(null);
container.setBackground(Color.PINK);
JLabel label = new JLabel("asdfghjkl;");
container.add(label);
}
}
这样在主窗口和弹窗中加的JLable都没有显示
原因:布局设置不对修改为这样即可显示
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//主窗口
public class JDialogDemo extends JFrame {
public JDialogDemo(String name) throws HeadlessException {
JFrame frame = new JFrame(name);
frame.setBounds(200,200,300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame的容器
Container container = frame.getContentPane();
//绝对布局
container.setLayout(new GridLayout(2,1));
container.setBackground(Color.CYAN);
JButton jButton = new JButton("弹窗");
jButton.setBounds(100,100,70,50);
JLabel label = new JLabel("superPower",SwingConstants.CENTER);
//点击按钮弹出一个弹窗
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new MyDialogDemo();
}
});
container.add(label);
container.add(jButton);
}
public static void main(String[] args) {
new JDialogDemo("主窗口");
}
}
//弹窗窗口
class MyDialogDemo extends JDialog{
public MyDialogDemo() {
JDialog dialog = new JDialog();
dialog.setTitle("弹窗");
dialog.setVisible(true);
dialog.setBounds(500,500,500,500);
//this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);自带关闭监听
Container container = dialog.getContentPane();
//container.setLayout(null);
container.setBackground(Color.PINK);
JLabel label = new JLabel("asdfghjkl;");
container.add(label);
}
}
er.setBackground(Color.PINK);
JLabel label = new JLabel(“asdfghjkl;”);
container.add(label);
}
}