将我的数组列表中的随机项放入JLabel

时间:2015-10-07 01:13:19

标签: java arrays swing user-interface

您好我在这个项目中遇到了一些问题我需要从数组中添加一个随机项目" anagrams"进入JLabel output_array。以下是我到目前为止的情况。我不确定应该如何调用它或者我应该创建一个JLabel数组?

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

}

1 个答案:

答案 0 :(得分:1)

解决方案是使用类似Random

的内容
//...
private String[] answers;
private String[] anagrams;

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

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

您当然可以存储int值,以便您知道匹配的答案是什么;)