在Java中,如何使数组中的每个元素成为一个按钮?

时间:2013-11-24 20:39:09

标签: java arrays jbutton

对于我的CS项目,我正在进行多项选择测验。每个测验都有一个问题和四个可能的答案。正确答案保存为字符串。所有错误的答案都保存在一个字符串数组中。我想为每个人制作一个按钮。但我不希望正确的答案始终处于相同的位置,所以我想随机放置它。在我随机放置之后,我不知道如何为字符串数组制作按钮。救命!

`     public Display(){

    answer1 = new JButton("1");
    answer2 = new JButton("2");
    answer3 = new JButton("3");
    answer4 = new JButton("");
    question = new JLabel ("question?");
}

public Display(String question1, String [] answers, String correct, String pictureName){
    //create a panel to hold buttons

    SimplePicture background = new SimplePicture(pictureName);
    JLabel picture = background.getJLabel();

    question = new JLabel(question1);

    //assign answers to buttons

    //generate a random number to determine where correct goes
    int index = (int)(Math.random()*4);

    //place correct answer in a certain button
    if (index == 0){
        answer1 = new JButton(correct);
    }
    else if (index == 1){
        answer2 = new JButton(correct);
    }
    else if (index == 2){
        answer3 = new JButton(correct);
    }
    else if (index == 3){
        answer4 = new JButton(correct);
    }

    //fill other spots with answers
    for (int i=0; i < answers.length; i++){
        this is where I need help

        }
    }`

1 个答案:

答案 0 :(得分:0)

修改

现在回答你的问题:

由于您事先知道有多少个按钮,因此您可以简单地使用数组。

JButton[] buttons;

buttons = new JButton[4] // or new JButton[answers.length] if you ever 
                         // want to increase the amount of answers.

//assign answers to buttons

//generate a random number to determine where correct goes
int index = (int)(Math.random() * 4);

//put the correct answer to the random button:
buttons[index] = new JButton(correct)

//fill other spots with answers
for (int i = 1; i <= answers.length; i++) {
    buttons[(index + i) % answers.length] = new JButton(answers[i - 1]);
}

所以如果你不知道%是java中的模数运算符,会发生什么呢。因此,如果(index + i)超过3(假设answers.length为3),它将再次变为0,因此您将无法获得IndexOutOfBoundsException

希望这有帮助。