java搞一个弹窗,不承认是猪就不让关闭
时间: 2023-06-19 10:05:07 浏览: 61
可以使用Java Swing组件库中的JOptionPane和JDialog来实现弹窗,并结合WindowAdapter和WindowEvent来阻止关闭操作。以下是一个例子:
```
import javax.swing.*;
import java.awt.event.*;
public class NotPigDialog extends JDialog {
public NotPigDialog(JFrame parent) {
super(parent, "确认身份", true);
JPanel panel = new JPanel();
JLabel label = new JLabel("你确认你不是一只猪吗?");
panel.add(label);
JButton button = new JButton("确认");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panel.add(button);
add(panel);
pack();
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(null, "不承认是猪就不能关闭!");
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame("测试");
JButton button = new JButton("点击弹窗");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
NotPigDialog dialog = new NotPigDialog(frame);
dialog.setVisible(true);
}
});
frame.add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
```
这个例子中,我们创建了一个继承自JDialog的类NotPigDialog,并在构造函数中添加了一个JPanel和一个JButton。JPanel中添加了一个JLabel和一个JButton,JButton的点击事件会关闭弹窗。在NotPigDialog的构造函数中,我们还通过addWindowListener方法添加了一个WindowAdapter,来监听弹窗关闭事件。在WindowAdapter中,我们重写了windowClosing方法,当用户试图关闭弹窗时,会弹出一个JOptionPane提示用户不承认是猪就不能关闭。
在main方法中,我们创建了一个JFrame,添加了一个JButton,当点击按钮时会弹出NotPigDialog弹窗。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)