您现在的位置是:首页 > 编程 > 

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

2025-07-27 15:21:37
使用Swing制作一个产生随机数的程序 使用Swing制作一个产生随机数的程序效果演示本文将详细介绍如何使用Swing库编写一个产生随机数的程序。该程序具有一个用户界面,用户可以输入左边界和右边界,并点击按钮生成一个介于左右边界之间的随机数。同时,程序还包括一些用于处理边界情况和可选的时间显示功能。程序结构这个程序通过创建一个继承自JFrame类的RandomumberGenerator类来实现

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

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

效果演示

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

程序结构

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

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

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

生成随机数

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

代码语言:javascript代码运行次数:0运行复制
int leftBound, rightBound;

// 处理左边界
try {
    leftBound = Integer.parseInt(leftTextField.getText());
} catch (umberFormatException ex) {
    leftBound = 0;
}

// 处理右边界
try {
    rightBound = Integer.parseInt(rightTextField.getText());
} catch (umberFormatException ex) {
    rightBound = leftBound + 100; // 默认:左边界 + 100
}

// 如果右边界小于左边界,交换值
if (rightBound < leftBound) {
    int temp = rightBound;
    rightBound = leftBound;
    leftBound = temp;
}

int randomumber = getRandomumber(leftBound, rightBound);
resultLabel.setText((randomumber));
处理边界情况

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

时间显示功能

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

如何使用程序

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

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

完整代码
代码语言:javascript代码运行次数:0运行复制
import javax.swing.*;
import java.awt.*;
import java.ActionEvent;
import java.ActionListener;
import SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class RandomumberGenerator 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 RandomumberGenerator() {
        setTitle("Random umber Generator");
        setSize(400, 00);
        setDefaultCloseOperation(JFrame.EXIT_O_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, 0));
        resultPanel.add(resultLabel);

        generateButton = new JButton("Generate Random umber");
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int leftBound, rightBound;

                // Handle left bound
                try {
                    leftBound = Integer.parseInt(leftTextField.getText());
                } catch (umberFormatException ex) {
                    leftBound = 0;
                }

                // Handle right bound
                try {
                    rightBound = Integer.parseInt(rightTextField.getText());
                } catch (umberFormatException 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 randomumber = getRandomumber(leftBound, rightBound);
                resultLabel.setText((randomumber));
            }
        });

        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.ORTH);
        add(resultPanel, BorderLayout.CETER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private int getRandomumber(int min, int max) {
        int range = max - min + 1;
        Random random = new Random();
        return (range) + min;
    }

    private void showInstruction() {
        String instruction = "Instructi:\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.IFORMATIO_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.ORTH);
            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((10, 0, 10, 0));
            getContentPane().add(timeLabel, BorderLayout.CETER);
            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.getSystemLookAndFeelClassame());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                new RandomumberGenerator().setVisible(true);
            }
        });
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-01-20,如有侵权请联系 cloudcommunity@tencent 删除swing程序定时器addprivate

#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格

本文地址:http://www.dnpztj.cn/biancheng/1144592.html

相关标签:无
上传时间: 2025-07-19 10:58:04
留言与评论(共有 8 条评论)
本站网友 冬瓜炖排骨
11分钟前 发表
rightBound; // Handle left bound try { leftBound = Integer.parseInt(leftTextField.getText()); } catch (umberFormatException ex) { leftBound = 0; } // Handle right bound try { rightBound = Integer.parseInt(rightTextField.getText()); } catch (umberFormatException ex) { rightBound = leftBound + 100; // Default
本站网友 沙瑞金
24分钟前 发表
new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String currentTime = getCurrentTime(); timeLabel.setText("Current Time
本站网友 deviceid
16分钟前 发表
以了解如何正确使用该程序
本站网友 咳嗽的治疗
3分钟前 发表
显示当前时间的标签
本站网友 九江租房
22分钟前 发表
我们会交换它们的值
本站网友 网线的顺序
21分钟前 发表
用户可以在程序界面上切换显示当前时间的标签
本站网友 怎样去眼角皱纹
14分钟前 发表
我们首先获取用户输入的左右边界值