使用Swing制作一个产生随机数的程序

简介: 使用Swing制作一个产生随机数的程序

使用Swing制作一个产生随机数的程序

效果演示

本文将详细介绍如何使用Swing库编写一个产生随机数的程序。该程序具有一个用户界面,用户可以输入左边界和右边界,并点击按钮生成一个介于左右边界之间的随机数。同时,程序还包括一些用于处理边界情况和可选的时间显示功能。

程序结构

这个程序通过创建一个继承自JFrame类的RandomNumberGenerator类来实现。它包括以下组件:

  • resultLabel: 用于显示随机数的标签。
  • leftTextField: 用户输入左边界的文本框。
  • rightTextField: 用户输入右边界的文本框。
  • generateButton: 生成随机数的按钮。
  • displayTimeButton: 切换时间显示的按钮。
  • timeLabel: 显示当前时间的标签。

程序的主要逻辑在构造函数RandomNumberGenerator()中实现。在构造函数中,我们设置了窗口的标题、大小和布局,并添加了输入面板、结果面板和按钮面板。

生成随机数

在按钮的ActionListener中,我们首先获取用户输入的左右边界值。如果用户没有输入值,我们将默认边界设置为0到100。然后根据指定的边界范围来生成一个随机数,并将其显示在resultLabel上。

int leftBound, rightBound;
// 处理左边界
try {
    leftBound = Integer.parseInt(leftTextField.getText());
} catch (NumberFormatException ex) {
    leftBound = 0;
}
// 处理右边界
try {
    rightBound = Integer.parseInt(rightTextField.getText());
} catch (NumberFormatException ex) {
    rightBound = leftBound + 100; // 默认:左边界 + 100
}
// 如果右边界小于左边界,交换值
if (rightBound < leftBound) {
    int temp = rightBound;
    rightBound = leftBound;
    leftBound = temp;
}
int randomNumber = getRandomNumber(leftBound, rightBound);
resultLabel.setText(Integer.toString(randomNumber));

处理边界情况

为了处理用户可能出现的不合法输入,我们在生成随机数之前对边界值进行了一些处理。如果用户没有输入左边界,我们将左边界设为0;如果用户没有输入右边界,则默认将右边界设置为左边界加上100。此外,如果右边界小于左边界,我们会交换它们的值,以确保生成的随机数在用户指定的范围内。

时间显示功能

该程序还提供了可选的时间显示功能。通过点击"Toggle Time Display"按钮,用户可以在程序界面上切换显示当前时间的标签。当用户点击该按钮时,我们会根据timeVisible变量的值来切换时间显示的状态。如果时间显示可见,我们会创建一个定时器Timer,每隔1秒更新一次时间,并将其显示在timeLabel上。如果时间显示不可见,我们会停止定时器并清空timeLabel。

如何使用程序

运行程序后,用户可以输入左边界和右边界的值。然后点击"Generate Random Number"按钮即可生成一个介于左右边界之间的随机数,并显示在界面上。另外,用户还可以点击"Info"按钮来查看使用说明,以了解如何正确使用该程序。

这个程序的目标是帮助初学者理解并熟悉Swing库的使用方法,以及如何编写一个简单的交互式应用程序。通过阅读和理解这段代码,你可以尝试自己编写类似的程序,或对现有代码进行修改和扩展,以满足自己的需求。

完整代码

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class RandomNumberGenerator extends JFrame {
    private JLabel resultLabel;
    private JTextField leftTextField;
    private JTextField rightTextField;
    private JButton generateButton;
    private JButton displayTimeButton;
    private boolean timeVisible = false; // Indicates if the time display is currently visible
    private JLabel timeLabel;
    private Timer timer;
    public RandomNumberGenerator() {
        setTitle("Random Number Generator");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        JPanel inputPanel = new JPanel(new FlowLayout());
        JLabel leftLabel = new JLabel("Left Bound:");
        inputPanel.add(leftLabel);
        leftTextField = new JTextField(5);
        inputPanel.add(leftTextField);
        JLabel rightLabel = new JLabel("Right Bound:");
        inputPanel.add(rightLabel);
        rightTextField = new JTextField(5);
        inputPanel.add(rightTextField);
        JPanel resultPanel = new JPanel(new FlowLayout());
        resultLabel = new JLabel();
        resultLabel.setFont(new Font("Arial", Font.BOLD, 30));
        resultPanel.add(resultLabel);
        generateButton = new JButton("Generate Random Number");
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int leftBound, rightBound;
                // Handle left bound
                try {
                    leftBound = Integer.parseInt(leftTextField.getText());
                } catch (NumberFormatException ex) {
                    leftBound = 0;
                }
                // Handle right bound
                try {
                    rightBound = Integer.parseInt(rightTextField.getText());
                } catch (NumberFormatException ex) {
                    rightBound = leftBound + 100; // Default: left bound + 100
                }
                // Swap values if right bound is smaller than left bound
                if (rightBound < leftBound) {
                    int temp = rightBound;
                    rightBound = leftBound;
                    leftBound = temp;
                }
                int randomNumber = getRandomNumber(leftBound, rightBound);
                resultLabel.setText(Integer.toString(randomNumber));
            }
        });
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton infoButton = new JButton("Info");
        infoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showInstruction();
                addDisplayTimeButton();
            }
        });
        buttonPanel.add(generateButton);
        buttonPanel.add(infoButton);
        add(inputPanel, BorderLayout.NORTH);
        add(resultPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    private int getRandomNumber(int min, int max) {
        int range = max - min + 1;
        Random random = new Random();
        return random.nextInt(range) + min;
    }
    private void showInstruction() {
        String instruction = "Instructions:\n"
                + "- Input a left bound and right bound for the random number range.\n"
                + "- If no values are specified, the range defaults to 0 to 100.\n"
                + "- If only the left bound is specified, the right bound will be left bound + 100.\n"
                + "- If only the right bound is specified, the left bound will be right bound - 100.\n"
                + "- If the right bound is smaller than the left bound, they will be swapped.\n";
        JOptionPane.showMessageDialog(this, instruction, "How to Use", JOptionPane.INFORMATION_MESSAGE);
    }
    private void addDisplayTimeButton() {
        if (displayTimeButton == null) {
            displayTimeButton = new JButton("Toggle Time Display");
            displayTimeButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    toggleTimeDisplay();
                }
            });
            JPanel buttonPanel = new JPanel(new FlowLayout());
            buttonPanel.add(displayTimeButton);
            getContentPane().add(buttonPanel, BorderLayout.NORTH);
            revalidate();
        }
    }
    private void toggleTimeDisplay() {
        timeVisible = !timeVisible;
        if (timeVisible) {
            updateTimeLabel();
        } else {
            timer.stop();
            timeLabel.setText("");
        }
    }
    private void updateTimeLabel() {
        if (timeLabel == null) {
            timeLabel = new JLabel();
            timeLabel.setFont(new Font("Arial", Font.BOLD, 16));
            timeLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
            getContentPane().add(timeLabel, BorderLayout.CENTER);
            revalidate();
        }
        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String currentTime = getCurrentTime();
                timeLabel.setText("Current Time: " + currentTime);
            }
        });
        timer.start();
    }
    private String getCurrentTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date currentTime = new Date();
        return dateFormat.format(currentTime);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                new RandomNumberGenerator().setVisible(true);
            }
        });
    }
}
相关文章
|
XML Java 数据库连接
解决在mybatis中出现的org.apache.ibatis.exceptions.PersistenceException~
解决在mybatis中出现的org.apache.ibatis.exceptions.PersistenceException~
2938 0
|
安全 Linux
CentOS下载ISO镜像的方法
访问CentOS官方网站(https://www.centos.org/download/),在“Downloads”页面找到ISO镜像下载链接,选择所需版本和架构(如x86_64)开始下载。CentOS分为Linux版和Stream版,前者每两年发行一次并提供10年安全维护,后者为滚动更新。旧版本可在Vault(https://vault.centos.org/)下载。建议选择DVD格式镜像,包含完整系统和常用软件。
41562 16
CentOS下载ISO镜像的方法
|
传感器 网络协议 Linux
DPDK如何赋能EtherCAT
DPDK如何赋能EtherCAT
|
网络协议 Linux Ruby
CentOS7各个版本镜像下载地址
CentOS7各个版本镜像下载地址
51303 0
|
存储 算法 数据处理
【数据结构】静态表查找之顺序查找、二分查找、分块查找
【数据结构】静态表查找之顺序查找、二分查找、分块查找
1277 0
【数据结构】静态表查找之顺序查找、二分查找、分块查找
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8048 1
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18032 63