使用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);
            }
        });
    }
}
相关文章
|
12月前
|
机器学习/深度学习 人工智能 自然语言处理
前端大模型入门(三):编码(Tokenizer)和嵌入(Embedding)解析 - llm的输入
本文介绍了大规模语言模型(LLM)中的两个核心概念:Tokenizer和Embedding。Tokenizer将文本转换为模型可处理的数字ID,而Embedding则将这些ID转化为能捕捉语义关系的稠密向量。文章通过具体示例和代码展示了两者的实现方法,帮助读者理解其基本原理和应用场景。
2955 1
|
数据管理 API 调度
阿里云百炼平台知识检索应用评测:搭建之旅与一点建议
阿里云百炼平台成为企业智能化转型的重要工具之一。
|
Linux C语言
成功解决 在Linux CentOS 7 中安装gcc
这篇文章介绍了如何在Linux CentOS 7系统中安装gcc (g++) 8工具集。由于CentOS 7默认的gcc版本是4.8,而这个版本与Qt 5.14、Qt 5.15或更高版本不兼容,可能会导致编译时出现系统头文件错误。文章中提到,即使在项目配置中添加了`CONFIG+=c++11`,如果仍然报错,那么很可能是gcc版本的问题。为了解决这个问题,文章提供了使用CentOS的Software Collections (scl)来安装更新版本的gcc的步骤。
成功解决 在Linux CentOS 7 中安装gcc
|
存储 数据库 数据安全/隐私保护
RAM账号快速入门
RAM账号快速入门
779 0
|
缓存 Linux API
冲破内核限制:使用DPDK提高网络应用程序的性能(上)
冲破内核限制:使用DPDK提高网络应用程序的性能
|
缓存 网络协议 数据挖掘
如何使用弱网环境来验证游戏中的一些延迟问题
如何使用弱网环境来验证游戏中的一些延迟问题
|
存储 SQL JSON
5、DataX(DataX简介、DataX架构原理、DataX部署、使用、同步MySQL数据到HDFS、同步HDFS数据到MySQL)(一)
5、DataX(DataX简介、DataX架构原理、DataX部署、使用、同步MySQL数据到HDFS、同步HDFS数据到MySQL)(一)
|
机器人 Java 开发工具
生成指定长度的随机数字,用对方法精准提效数10倍!
生成指定长度的随机数字这一函数功能可能在以下情况下被使用:
|
弹性计算 运维 安全
RAM账号权限管理
希望通过本次演讲,让大家更深入了解RAM账号权限管理,以某电商网站项目为例,根据研发、测试、生产环境划分及业务流程,使用阿里云RAM访问控制服务规划实现资源分组、账号用户体系、权限分配、安全加固、定期安全检查等措施的最佳实践。
2399 1
RAM账号权限管理
|
存储 网络协议 Java
【分布式】Zookeeper序列化及通信协议
  前面介绍了Zookeeper的系统模型,下面进一步学习Zookeeper的底层序列化机制,Zookeeper的客户端与服务端之间会进行一系列的网络通信来实现数据传输,Zookeeper使用Jute组件来完成数据的序列化和反序列化操作。
220 0
【分布式】Zookeeper序列化及通信协议