javaswing随机数
时间: 2023-07-18 10:12:21 浏览: 87
生成随机数可以使用Java中的Random类。以下是使用Java Swing生成随机数的示例代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RandomNumberGenerator extends JFrame implements ActionListener {
private JButton generateButton;
private JLabel randomNumberLabel;
public RandomNumberGenerator() {
setTitle("Random Number Generator");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
generateButton = new JButton("Generate");
generateButton.addActionListener(this);
panel.add(generateButton);
randomNumberLabel = new JLabel();
panel.add(randomNumberLabel);
add(panel);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == generateButton) {
int randomNumber = (int) (Math.random() * 100);
randomNumberLabel.setText("Random Number: " + randomNumber);
}
}
public static void main(String[] args) {
RandomNumberGenerator rng = new RandomNumberGenerator();
rng.setVisible(true);
}
}
```
在这个示例中,当用户点击“生成”按钮时,将会生成一个0-99之间的随机数,并将其显示在标签上。
阅读全文