弹窗是指打开网页、软件、手机APP等的时候自动弹出的窗口。
现在我们用Swing来简单的实现弹窗的功能。
示例代码如下:
package Swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogDemo extends JFrame {
public DialogDemo() {
this.setTitle("这是主窗口");
this.setVisible(true);
this.setBounds(100,100,500,400);
Container container = this.getContentPane();//实例化容器
Button button = new Button("Point me");
button.setBounds(50,50,100,100);
button.setVisible(true);
container.setLayout(null);//设置容器的定位为绝对定位
//添加按钮的监听事件,当点击按钮,对mydialogdemo这个类进行实例化
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new mydialogdemo();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo();
}
}
class mydialogdemo extends JDialog{
public mydialogdemo() {
this.setVisible(true);
this.setTitle("这是弹窗");
this.setBounds(600,400,400,200);
Container container=this.getContentPane();//实例化容器
container.setLayout(null);
Label label = new Label("Thank you for watching ! I hope it will help you");
label.setVisible(true);
label.setSize(300,50);
container.add(label);//将文本标签放进容器里面
}
}
运行的效果: