[April Fool's Day applet] Simple use of Java Swing

We use the Java Swing GUI library to create our small program that will pop up an alert window when the user clicks a button, and an April Fool's joke on the window when the user presses the "Go" button.

Here is an example of Java code that implements this functionality:

import javax.swing.*;

public class AprilFoolsGUI {
    public static void main(String[] args) {
        // 创建一个名为“安全中心”的JFrame窗口对象
        JFrame frame = new JFrame("安全中心");
        // 创建一个JPanel面板对象
        JPanel panel = new JPanel();
        // 创建一个带有警告文本的JLabel标签对象
        JLabel label = new JLabel("您的计算机正在遭受攻击!请按以下步骤保护您的计算机:");
        // 创建一个名为“执行”的JButton按钮对象
        JButton executeButton = new JButton("执行");
        // 创建一个名为“取消”的JButton按钮对象
        JButton cancelButton = new JButton("取消");

        // 将JLabel和JButton添加到JPanel面板对象中
        panel.add(label);
        panel.add(executeButton);
        panel.add(cancelButton);

        // 将JPanel面板对象添加到JFrame窗口对象中
        frame.add(panel);

        // 设置JFrame窗口的大小为宽400像素,高150像素
        frame.setSize(400, 150);

        // 设置点击JFrame窗口右上角的关闭按钮时,程序自动退出
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 为“执行”按钮添加单击事件监听器
        executeButton.addActionListener(e -> {
            // 弹出你被骗了,愚人节快乐!
            JOptionPane.showMessageDialog(frame, "你被骗了,愚人节快乐!");
        });

        // 为“取消”按钮添加单击事件监听器
        cancelButton.addActionListener(e -> {
            // 弹出可恶,还是被你发现了
            JOptionPane.showMessageDialog(frame, "可恶,还是被你发现了!");
            // 关闭程序
            System.exit(0);
        });

        // 设置JFrame窗口可见
        frame.setVisible(true);
    }
}

The effect of running the program is as follows:

 Click to execute the effect as follows:

The effect of clicking cancel is as follows:

 

Guess you like

Origin blog.csdn.net/m0_56170277/article/details/129904535