user5416323
user5416323

Reputation: 11

Putting a random item from my array list into the JLabel

Hello I am having some issues with this project I need to put a random item from the array "anagrams" into the JLabel output_array. Here is what I have so far.I am unsure how I should call it or Should I make a JLabel array?

public class Scramble extends JFrame {
private String[] answers;
private String[] anagrams;

private JButton check = new JButton("CHECK");
private JButton give_up = new JButton("GIVE UP?");

private JTextField input = new JTextField(25); 

private JLabel output_array = new JLabel(anagrams[1]); 


//for output of anagram
private JLabel output_1 = new JLabel("HERE IS AN ANAGRAM"); 

private JPanel main_panel = new JPanel();



//constructor
public Scramble()
{
    setTitle("Anagram");
    main_panel.setBackground(Color.ORANGE);

    main_panel.add(output_1);

    main_panel.add(output_array);

    main_panel.add(input);
    main_panel.add(check);
    main_panel.add(give_up);

    this.add(main_panel);
}



public void answers_array()
{
    answers = new String[]
    {
    "DEALER",
    "FARMER",
    "BAKER",
    "AIDE",
    "PAINTER",
    "SENATOR",
    "SALESMAN",
    "ORGANIST",
    "TEACHER",
    "MARINE"
    };
}

public void anagram_array()
{
    anagrams = new String[]
    {
    "DEALER",
    "FRAMER",
    "BREAK",
    "IDEA",
    "REPAINT",
    "TREASON",
    "NAMELESS",
    "ROASTING",
    "CHEATER",
    "REMAIN"
    };
}


public static void main(String[] args)
{
    Scramble frame = new Scramble();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);

}

Upvotes: 1

Views: 106

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347234

A solution would be to use something like Random

//...
private String[] answers;
private String[] anagrams;

private Random random = new Random();
//...

String anagram = anagrams[random.nextInt(anagrams.length)];
output_array.setText(anagram);

You of course might store the int value so you know the what the matching answer would be ;)

Upvotes: 1

Related Questions