Кнопка CardLayout меняется после 6 нажатий - PullRequest
0 голосов
/ 30 января 2019

Я пытаюсь создать тест.Тест начинается с чтения файла.В файле 6 вопросов.Каждый вопрос получает свою карточку в карточной раскладке.У каждой карты есть кнопка для следующего CardLayout.Вопросы 1 - 5 должны иметь кнопку «Далее», которая ссылается на следующую карточку.В вопросе 6 должна быть кнопка с надписью «получить результаты», которая будет ссылаться на карточку с одной из возможных карточек результатов.(они все еще находятся в процессе разработки, сейчас я просто пытаюсь создать кнопку и проверяю ее с помощью метода .previous ()).На данный момент каждая карта имеет следующую кнопку, и кажется, что утверждение, которое добавляет кнопку «получить результаты», не достигается.взглянуть.

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class UserInterface extends JPanel {
    public static final Object QUESTION = "question";
    // fill label with blank text to expand it
    private JLabel resultLabel = new JLabel(String.format("%150s", " "));

    // CardLayout to allow swapping of question panels
    private CardLayout cardLayout = new CardLayout();
    private JPanel centerPanel = new JPanel(cardLayout);
    private List<String> answers = new ArrayList<>();
    private int currentCard = 0; 
    private QuestionsContainer containers = new QuestionsContainer();

    public UserInterface(QuestionsContainer container) throws FileNotFoundException {
        centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        for (Questions question : container.getQuestions()) {
            centerPanel.add(createQPanel(question), null);
            currentCard++;

            JPanel bottomPanel = new JPanel(new BorderLayout());

            if ((currentCard == containers.questionsLength() - 1){
                bottomPanel.add(new JButton(new AbstractAction("Next") {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                    cardLayout.next(centerPanel);

                }
            }),
                BorderLayout.LINE_START);
                add(bottomPanel, BorderLayout.LINE_START);
                bottomPanel.add(resultLabel);

                setLayout(new BorderLayout());
                add(bottomPanel, BorderLayout.PAGE_END);
                add(centerPanel);
        }

                JPanel bottomPanel1 = new JPanel();
                bottomPanel1.add(new JButton(new AbstractAction("Get Results") {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("hello");
                        cardLayout.previous(centerPanel);
// both of these are just to see if this statement is reached
                        bottomPanel.validate();
                        bottomPanel.repaint();
                }
            }),
                BorderLayout.LINE_START);
                add(bottomPanel1, BorderLayout.LINE_START);
                bottomPanel1.add(resultLabel);

                setLayout(new BorderLayout());
                add(bottomPanel1, BorderLayout.PAGE_END);
                add(centerPanel);
        }    
    }

    private JPanel createQPanel(Questions question) {

        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
        radioPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        radioPanel.add(new JLabel(question.getQuestion()), BorderLayout.PAGE_START);
        ButtonGroup buttonGroup = new ButtonGroup();
        ItemListener myItemListener = new MyItemListener(this);
        for (String answer : question.getAnswer()) {
            JRadioButton answerButton = new JRadioButton(answer);

            answerButton.putClientProperty(QUESTION, question);
            answerButton.addItemListener(myItemListener);
            buttonGroup.add(answerButton);
            radioPanel.add(answerButton);
        }

        JPanel qPanel = new JPanel(new BorderLayout());
        qPanel.add(radioPanel);
        return qPanel;
    }

    public void displayResult(String selectedText) {
        resultLabel.setText(selectedText);
    }
    public void displayFinalResults(){

    }
    public static void createAndShowGui() throws FileNotFoundException {

        UserInterface mainPanel = new UserInterface(new QuestionsContainer());

        JFrame frame = new JFrame("User Interface");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

public class QuestionsContainer {

    private List<Questions> questions = new ArrayList<>();
    private int questionCount = 0;  

    QuestionsContainer() throws FileNotFoundException {

        File file = new File("src/house1.txt"); 
        try (Scanner reader = new Scanner(file)) {
            String question = "";
            List<String> answers = new ArrayList<>();

            while (reader.hasNextLine()){


                String line = reader.nextLine();
                if (line.startsWith("QUESTION: ")) {
                    question = line.substring(10);
                } else if (line.startsWith("ANSWER: ")){
                    String answer = line.substring(8);
                    answers.add(answer);
                } else if (line.isEmpty()) {
                    questions.add(new Questions(question, answers));
                    question = "";
                    answers = new ArrayList<>();
                    questionCount++;
                }
            }
        }
    }

    public List<Questions> getQuestions() {
        return questions;
    }
    public int questionsLength(){
        return questions.size();
    }

Я пытался сделать bottomPanel своим собственным методом, который возвращал bottomPanel.это не дало желаемых результатов, потому что оно вызывалось в конструкторе, и я не думаю, что переменная currentCard добавлялась каждый раз.Прямо сейчас этот код хорошо читает все вопросы и все ответы в порядке.Но он создает следующую кнопку на каждой карте, а не только на первых 5.если в странном месте есть переменная или подозрительный вызов печати, то, скорее всего, это оставшийся код предыдущего теста, который я забыл удалить / закомментировать.

1 Ответ

0 голосов
/ 30 января 2019

Вы, кажется, думаете с точки зрения процедурного процесса, а не процесса, управляемого событиями.Состояние currentCard будет обновляться во время каждого цикла, его состояние не «сохраняется» между итерациями.

Это означает, что в качестве побочного эффекта BorderLayout только последний компонент, добавленный в контейнер, будет

Вместо этого вам нужно изменить свое мышление, чтобы при срабатывании ActionListener вы обновляли состояние и определяли, что следует делать, например,

public UserInterface(QuestionsContainer container) throws FileNotFoundException {
    setLayout(new BorderLayout());
    centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
    for (Questions question : container.getQuestions()) {
        centerPanel.add(createQPanel(question), null);
    }
    add(centerPanel);

    JPanel navigationPane = new JPanel(new GridBagLayout());
    navigationPane.setBorder(new EmptyBorder(8, 8, 8, 8));
    JButton navButton = new JButton("Next");
    navButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (evt.getActionCommand().equals("Next")) {
                currentCard++;
                if (currentCard == container.questionsLength()) {
                    ((JButton) evt.getSource()).setText("Get results");
                }
                cardLayout.next(centerPanel);
            } else {
                System.out.println("Print the results");
            }
        }
    });
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.EAST;
    gbc.weightx = 1;
    navigationPane.add(navButton, gbc);
    add(navigationPane, BorderLayout.SOUTH);
}
...