java随机数滚动抽奖界面设计
时间: 2023-07-18 21:04:10 浏览: 188
以下是一个简单的 Java 随机数滚动抽奖界面设计示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Lottery extends JFrame implements ActionListener {
private JLabel label;
private JButton buttonStart, buttonStop;
private Timer timer;
private int number;
private boolean isRunning;
public Lottery() {
super("抽奖");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new BorderLayout());
label = new JLabel("点击开始按钮开始抽奖", JLabel.CENTER);
label.setFont(new Font("宋体", Font.BOLD, 20));
add(label, BorderLayout.CENTER);
JPanel panel = new JPanel(new FlowLayout());
buttonStart = new JButton("开始");
buttonStart.addActionListener(this);
panel.add(buttonStart);
buttonStop = new JButton("停止");
buttonStop.addActionListener(this);
panel.add(buttonStop);
add(panel, BorderLayout.SOUTH);
timer = new Timer(100, this);
isRunning = false;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonStart) {
if (!isRunning) {
timer.start();
isRunning = true;
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
}
} else if (e.getSource() == buttonStop) {
if (isRunning) {
timer.stop();
isRunning = false;
buttonStart.setEnabled(true);
buttonStop.setEnabled(false);
JOptionPane.showMessageDialog(this, "恭喜您获得 " + number + " 号奖品!", "抽奖结果", JOptionPane.INFORMATION_MESSAGE);
}
} else if (e.getSource() == timer) {
number = (int) (Math.random() * 100);
label.setText("正在抽奖,幸运号码:" + number);
}
}
public static void main(String[] args) {
Lottery lottery = new Lottery();
lottery.setVisible(true);
}
}
```
运行该程序后,会显示一个抽奖界面,点击开始按钮后,会随机生成一个幸运号码并滚动显示在界面上,再次点击停止按钮后,会弹出一个对话框显示抽奖结果。在程序中,使用了 Java 的定时器 Timer 来控制随机数的滚动,并且通过 JButton 按钮的 ActionListener 监听器来响应用户的操作。
阅读全文