gpt4 book ai didi

java - 将数组列表中的随机项目放入 JLabel

转载 作者:行者123 更新时间:2023-11-30 07:53:44 26 4
gpt4 key购买 nike

您好,我在这个项目中遇到一些问题,我需要将数组“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);

}

最佳答案

解决方案是使用诸如Random之类的东西

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

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

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

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

关于java - 将数组列表中的随机项目放入 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com