0

Всем привет! Хочу сделать тест с вопросами и картинками к ним.

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

Пожалуйста, можно подробнее. Не совсем разбираюсь.

Файл Quiz

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.CardLayout;
import java.util.Random;
import javax.swing.JOptionPane;

public class Quiz extends JFrame{
    JPanel p=new JPanel();
    CardLayout cards=new CardLayout();
    int numQs;
    int wrongs=0;
    int total=0;

    String[][] answers={
        {"Enschede","Amsterdam","Den Haag","Berlin"},
        {"Slang for Hankechief","Dutch for Keyboard","A Male Sheep","Width of a Cut"},
        {"Euler","Erasmus","Fibonnaci","Archemides"},
        {"Shadow of the Collosus","Lighthouse of Alexandria","Colliseum","Parthanon"},
        {"Cars","Nothing","Planes","Plastic Materials"},
        {"True","False"},
        {"True","False"},
        {"4","5","6","7"},
        {"The Lion King","Hamlet","Death of The Salesmen","Phantom of the Opera"},
    };

    RadioQuestion questions[]={

        new RadioQuestion(
            "What is the capital of the Netherlands?",
            answers[0],
            1,this
        ),
        new RadioQuestion(
            "What is a kerf?",
            answers[1],
            3,this
        ),
        new RadioQuestion(
            "Who discovered the number e?",
            answers[2],
            0,this
        ),
        new RadioQuestion(
            "Which of the following is one of the 7 wonders of the ancient world?",
            answers[3],
            1,this
        ),
        new RadioQuestion(
            "Which of the following is not made in China?",
            answers[4],
            1,this
        ),
        new RadioQuestion(
            "True or False, Driving drunk is more dangerous than driving tired",
            answers[5],
            1,this
        ),
        new RadioQuestion(
            "True or False, The Platypus is a mammal",
            answers[6],
            0,this
        ),
        new RadioQuestion(
            "How many strings are there on a standard guitar?",
            answers[7],
            2,this
        ),
        new RadioQuestion(
            "Which of these plays is made by shakespeare?",
            answers[8],
            1,this
        )
    };

    public static void main(String args[]){
        new Quiz();
    }

    public Quiz(){
        super("Quiz Game");
        setResizable(true);
        setSize(500,400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        p.setLayout(cards);
        numQs=questions.length;
        for(int i=0;i<numQs;i++){
            p.add(questions[i],"q"+i);
        }
        Random r=new Random();
        int i=r.nextInt(numQs);
        cards.show(p,"q"+i);
        add(p);
        setVisible(true);
    }

    public void next(){
        if((total-wrongs)==numQs){
            showSummary();
        }else{
            Random r=new Random();
            boolean found=false;
            int i=0;
            while(!found){
                i=r.nextInt(numQs);
                if(!questions[i].used){
                    found=true;
                }
            }
            cards.show(p,"q"+i);
        }
    }

    public void showSummary(){
        JOptionPane.showMessageDialog(null,"All Done :), here are your results"+
            "\nNumber of incorrect Answers: \t"+wrongs+
            "\nNumber of Correct Answers: \t"+(total-wrongs)+
            "\nAverage Incorrect Answers per Quesiotn: \t"+((float)wrongs/numQs)+
            "\nPercent Correct: \t\t"+(int)(((float)(total-wrongs)/total)*100)+"%"
        );
        System.exit(0);
    }
}

Файл RadioQuestion

import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;



public class RadioQuestion extends JPanel implements ActionListener{
    int correctAns;
    Quiz quiz;  
    int selected;
    boolean used;
    //questions
    JPanel qPanel=new JPanel();
    //answers
    JPanel aPanel=new JPanel();
    JRadioButton[] responses;
    ButtonGroup group=new ButtonGroup();
    //bottom
    JPanel botPanel=new JPanel();
    JButton next=new JButton("Next");
    JButton finish=new JButton("Finish");

    /*public static void main(String args[]){
        JFrame frame=new JFrame("RadioButton Test");
        frame.setSize(400,300);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setResizable(true);

        String[] answers={"wrong1","right","wrong2"};
        frame.add(new RadioQuestion("what's right?",answers,1));

        frame.setVisible(true);
    }*/

    public RadioQuestion(String q, String[] options, int ans, Quiz quiz){
        this.quiz=quiz;
        setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
        correctAns=ans;
        //question
        qPanel.add(new JLabel(q));
        add(qPanel);
        //answer
        responses=new JRadioButton[options.length];
        for(int i=0;i<options.length;i++){
            responses[i]=new JRadioButton(options[i]);
            responses[i].addActionListener(this);
            group.add(responses[i]);
            aPanel.add(responses[i]);
        }
        add(aPanel);
        //bottom
        next.addActionListener(this);
        finish.addActionListener(this);
        botPanel.add(next);
        botPanel.add(finish);
        add(botPanel);
    }

    public void actionPerformed(ActionEvent e){
        Object src=e.getSource();
        //next button
        if(src.equals(next)){
            showResult();
            if(selected==correctAns){
                used=true;
                quiz.next();
            }
        }
        //finish button
        if(src.equals(finish)){
            quiz.showSummary();
        }
        //radio buttons
        for(int i=0;i<responses.length;i++){
            if(src==responses[i]){
                selected=i;
            }
        }
    }

    public void showResult(){
        String text=responses[selected].getText();
        quiz.total++;
        if(selected==correctAns){
            JOptionPane.showMessageDialog(null,text+" is correct\nWell Done :)");
        }else{
            quiz.wrongs++;
            JOptionPane.showMessageDialog(null,text+" is wrong\nSorry :(");
        }
    }
}
1
  • Для этого надо изучить коллекции.
    – Roman C
    4 мар 2019 в 16:26

1 ответ 1

0

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

Quiz.java

String images[] = {
"1.jpg",
"2.jpg",
"3.jpg", 
...
};

RadioQuestion questions[]={
    new RadioQuestion(
        "What is the capital of the Netherlands?",
        answers[0],
        1,this, images[0]
    ),
    new RadioQuestion(
        "What is a kerf?",
        answers[1],
        3,this, images[1]
    ),
    ...
}

RadioQuestion.java

public RadioQuestion(String q, String[] options, int ans, Quiz quiz, String path){
    ...
    responses=new JRadioButton[options.length];

    try{
        JPanel img = new JPanel();
        BufferedImage myPicture = ImageIO.read(new File(path));
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));
        img.add(picLabel);
        add(img);
    } catch (Exception e) {}
    ...
}

Сейчас ваша главная проблема в том, что вы размазываете данные по программе и не храните их в одном месте с легким досутом. Попробуйте использовать ООП и переписать вашу программу с классами, которые хранят данные вместе. Жизнь станет намного легче:

public class Question {
    public String Question;
    public String[] Answers;
    public int Answer;
    public String ImagePath;

    public Question(String question, ArrayList<String> answers, int answer, String imagePath){
        this.Question = question;
        this.Answer = answer;
        this.Answers = answers;
        this.ImagePath = imagePath;
    }
}

Конечно желательно еще отделять графический интерфейс и данные, но для этого придется переписать большую часть программы. Еще хорошим примером будет написать программу так, чтобы вопросы хранились во внешнем файле и вам не приходилось перекомпилировать ее каждый раз, когда вы хотите внести изменения в вопросы (добавить, удалить, исправить опечатку и т.д.).

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.