【Java】使用AI助手写一个简易抽奖器,手写代码0

2023-12-27 18:47:40

使用Java写一个抽奖器,多人参与则可以手动控制

public class LotteryMachine extends JFrame {
    //1-100 彩票预算机器
    private JLabel resultLabel;
    private JButton startButton;
    private boolean isRunning;

    public LotteryMachine() {
        super("抽奖机");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();

        resultLabel = new JLabel("点击开始抽奖");
        resultLabel.setFont(new Font("Arial", Font.PLAIN, 20));
        panel.add(resultLabel);

        startButton = new JButton("开始");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isRunning) {
                    isRunning = true;
                    startButton.setText("停止");
                    startLottery();
                } else {
                    isRunning = false;
                    startButton.setText("开始");
                }
            }
        });
        panel.add(startButton);

        add(panel);
    }

    private void startLottery() {
        Thread lotteryThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunning) {
                    int randomNumber = (int) (Math.random() * 100) + 1;
                    resultLabel.setText(String.valueOf(randomNumber));
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        lotteryThread.start();
    }

    public static void main(String[] args) {
        LotteryMachine lotteryMachine = new LotteryMachine();
        lotteryMachine.setVisible(true);
    }
}

效果图:开始后,第一个数字出现,第二个数字会延迟五秒出现……

在这里插入图片描述

文章来源:https://blog.csdn.net/like_start/article/details/135246804
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。