我正在尝试制作一个 Pinoy Henyo 游戏,我希望我的文本使用数组随机生成到我的 JLabel,有人可以帮助我吗?我试图在网上搜索,但找不到任何东西。这是我的一些代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SuperHenyo extends JFrame implements ActionListener {
String bagay[] = {
"Gitara", "Timba", "Tuwalya", "Telebisyon", "Laptop", "Bintilador", "Relo", "Jacket", "Medyas", "Bumbilya"
};
JButton bBtn = new JButton("BAGAY");
public SuperHenyo() {}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bBtn) {
}
最佳答案
您可以使用 java.util.Random
生成一个随机 int
值,它可以作为数组的索引
有点像...
Random rnd = new Random();
int index = rnd.nextInt(bagay.length);
String text = bagay[index];
但就我个人而言,我会创建 Random
作为类的实例字段并根据需要重复使用
参见 How to Use Labels有关如何使用 JLabel
关于java - 在数组中选择随机元素并将其放在 JLabel 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386742/