Pick a random item in the array and put it in the JLabel

I am trying to make a Pinoy Henyo game and I want my text to randomly generate my JLabel using an array, can anyone help me with this? I tried to search the net but can't find anything. Here are some of my code:

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) {

        }

      

+3


source to share


1 answer


You can use java.util.Random

to generate a random value int

that can act as an index in your array

Something like...

Random rnd = new Random();
int index = rnd.nextInt(bagay.length);
String text = bagay[index];

      



But personally I would Random

instantiate as a class instance field and reuse as needed

More on how to work with JLabel

s

see How to use shortcuts .
+3


source







All Articles