使用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);
            }
        });
    }
}

猜你喜欢

转载自blog.csdn.net/qq_51447496/article/details/131923839