Создайте логическое значение, чтобы показать true, когда выбраны правильные JRadioButtons

предыдущий связанный вопрос: Проверить, какие jRadioButtons были выбраны, если они были созданы в цикле

Теперь я хочу создать логическое значение, чтобы при выборе всех правильных JRadioButtons из каждой строки это логическое значение было истинным.

Чтобы уточнить, это может быть правдой только тогда, когда выбраны все переключатели, по одному из каждой строки, которые являются правильными.

Приведенный ниже код уже печатает строку строки и btn только тогда, когда выбран правильный JRadioButton, но я не уверен, как теперь реализовать это в том, что я ищу. заранее спасибо

//loop for making flow layout for each line of random letters
//counter for having number of the row next to each row in order of selection
int counter = x;
for(int i = 0; i < x; i++)
{
    //new jpanel created for every row needed for the word
    JPanel jpLine = new JPanel(new FlowLayout());

    //new jlabel made with counter number for each row
    JLabel count = new JLabel(Integer.toString(counter));
    jpLine.add(count);
    counter--;
    //random number from 0-5 generated for each row
    Random number = new Random();
    int low = 0;
    int high = 5;
    int ranNumber = number.nextInt((high - low) + low);

    //buttongroup outside loop so only one button can be pressed for each row
    ButtonGroup bg = new ButtonGroup();

    //get selected button's index in any group with bg.getSelection().getActionCommand()
    final int row = i;
    final ButtonGroup btnG = bg;
    ActionListener listener = new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {

            //correct.setText("correct");

            System.out.println("row " + row);
            System.out.println("btn " + btnG.getSelection().getActionCommand());



        }
    };

    //loop for making the number of letters in each row - always going to be 6 letters to choose from in each row
    for(int j = 0; j < 5; j++)
    {
        //if the random number generated for each row equals the loop
        //then new radiobutton will be created for the ith letter of the reversed
        //answer, starting from charAt 0 and going to the last character
        if(ranNumber == j)
        {
            JRadioButton answerLetter = new JRadioButton("<html><font color = 'white'>" + answerForGrid.charAt(i) + "</font></html>");

            bg.add(answerLetter);
            answerLetter.setBackground(Color.decode("#566771"));
            answerLetter.setOpaque(true);
            jpLine.add(answerLetter);

            //use setActionCommand("" + j) on each button to associate each button with its index
            answerLetter.setActionCommand("" + j);
            answerLetter.addActionListener(listener);
        }

        //ranLetter is generated randomly from the alphabet string, so random letters are
        //created for each jradiobutton
        final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        final int N = alphabet.length();

        Random letter = new Random();
        char ranLetter;

        while(true) 
        {
            ranLetter = alphabet.charAt(letter.nextInt(N));
            break;
        }

        JRadioButton k = new JRadioButton("<html><font color = 'white'>" + ranLetter + "</font></html>");

        bg.add(k);
        k.setBackground(Color.decode("#566771"));
        k.setOpaque(true);
        jpLine.add(k);
    }
    //add each row of letters (jpLine) to this loops jpanel
    jpCenterCenter.add(jpLine);
}

person AEkon    schedule 01.02.2015    source источник


Ответы (1)


Работая с вашим кодом, вы можете объявить массив логических значений перед начальным циклом следующим образом:

int counter = x;
boolean[] responses = new boolean[x]
for(int i = 0; i < x; i++)
{
     //new jpanel created for every row needed for the word
     JPanel jpLine = new JPanel(new FlowLayout());

Затем вы хотите отредактировать свой actionListener, чтобы переключить логическое значение строки на true при выборе. Важно отметить, что если вы сделаете это, вам нужно добавить прослушиватель к другим кнопкам, чтобы, если пользователь выбирает правильный выбор, а затем переключается на неправильный выбор, логическое значение возвращается к false.

ActionListener listener = new ActionListener() 
{
    public void actionPerformed(ActionEvent e) 
    {

        //correct.setText("correct");

        String action = e.getActionCommand();

        if (action.equals("Incorrect")) {
            reponses[row] = false;
        }
        else {
            responses[row] = true;
            System.out.println("row " + row);
            System.out.println("btn " + action);
        }


    }
};

Не забудьте добавить это к другим кнопкам здесь:

JRadioButton k = new JRadioButton("<html><font color = 'white'>" + ranLetter + "</font></html>");
k.setActionCommand("Incorrect");
k.addActionListener(listener);

Затем вы можете добавить отдельный метод, чтобы проверить, установлены ли для всех ответов значения true:

private boolean checkAnswers(boolean[] responses) {
    for (boolean b : responses) {
        if (!b) return false
    }
    return true;
}
person Matt Kormann    schedule 01.02.2015