Java - 在ButtonGroup内部的随机按钮

时间:2017-11-29 16:03:57

标签: java swing jradiobutton buttongroup

另外还有我之前的问题:Java - using a IsSelected function in radioButtons and JPanel

我有一个程序可以将按钮添加到按钮组和面板。

问题 - 在按钮组中按下按钮

我可以选择随机播放按钮组,但它不会随机播放组内的按钮。

以下是相关代码:

public void addButtonsToFrame(ArrayList<Question> q, int number_of_lines,
                              ArrayList<ButtonGroup> BG, ArrayList<JPanel> JP) {
    int j = 0;
    for (int i = 0; i < q.size(); i++) {
        qNumber = i + 1;
        BG.add(new ButtonGroup());
        JP.add(new JPanel());
        JP.get(i).setSize(499, 400);
        //creating buttons
        JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
        option1.setActionCommand(q.get(i).get_option1());
        JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
        option2.setActionCommand(q.get(i).get_option2());
        JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
        option3.setActionCommand(q.get(i).get_option3());
        JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
        option4.setActionCommand(q.get(i).get_option4());

        //adding to group buttons
        BG.get(j).add(option1);
        BG.get(j).add(option2);
        BG.get(j).add(option3);
        BG.get(j).add(option4);

        //Collections.shuffle(BG);
        //adding the buttons to the panel
        JP.get(j).add(option1);
        JP.get(j).add(option2);
        JP.get(j).add(option3);
        JP.get(j).add(option4);
        //setting layout that matches our goal
        this.setLayout(new GridLayout(number_of_lines + 1, 1));
        //set title and border for each question
        JP.get(i).setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(), "question number " + qNumber + ": " + q.get(i).get_question()));
        //adding the panel to the frame
        this.add(JP.get(j));
        //BG.get(i).getSelection()
        JP.get(j).setVisible(true);
        j++;

    }
}

1 个答案:

答案 0 :(得分:0)

正如其他用户之前建议的那样 - 我必须在添加到面板之前将按钮添加到ArrayList

我做到了,程序正常运作。

谢谢!

        JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
        option1.setActionCommand(q.get(i).get_option1());
        buttons.add(option1);
        JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
        option2.setActionCommand(q.get(i).get_option2());
        buttons.add(option2);
        JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
        option3.setActionCommand(q.get(i).get_option3());
        buttons.add(option3);
        JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
        option4.setActionCommand(q.get(i).get_option4());
        buttons.add(option4);
        Collections.shuffle(buttons);