【问题标题】:How to add images in windows with questions?如何在有问题的窗口中添加图像?
【发布时间】:2019-03-07 09:27:40
【问题描述】:

我想用问题和每个问题的独特图像进行测验。例如

我不知道为什么,但窗口中没有带有问题的图像。例如,在问题“荷兰的首都是什么?”的窗口中,没有来自文件“Quiz.java”的图像“information.jpg”。 如何在带有问题的窗口中放置图像,为每个问题放置独特的图像?请帮忙

当我选择了images book.jpg, science.jpg,wise.jpg : C:\Users\syuye\eclipse-workspace\test\src\test 的文件夹时,出现了错误提示

所以我将文件保存为 utf-8。也许它受到了某种影响?

to c0der:是的,我添加了 e.printStackTrace();

JLabel picLabel = new JLabel(new ImageIcon(myPicture));

img.add(picLabel); 

add(img); 

} catch (Exception e) {e.printStackTrace();}

发生错误:

javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:42)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:47)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:52)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:57)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:62)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:67)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:72)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:77)
    at test.Quiz.main(Quiz.java:90)
javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at test.RadioQuestion.<init>(RadioQuestion.java:61)
    at test.Quiz.<init>(Quiz.java:82)
    at test.Quiz.main(Quiz.java:90)

Quiz.java 文件

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

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"},
    };

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

    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.java 文件

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; 
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.imageio.*;
import java.io.*;

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];

        try{
            JPanel img = new JPanel();
            BufferedImage myPicture = ImageIO.read(new File("‪‪‪C:\Users\syuye\eclipse-workspace\test\src\test")); 
            JLabel picLabel = new JLabel(new ImageIcon(myPicture));
            img.add(picLabel);
            add(img);
        } catch (Exception e) {e.printStackTrace();}

        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 :(");
        }
    }
}

【问题讨论】:

  • 我的猜测是程序抛出异常。请张贴。 (您可能看不到异常,因为您对它们什么都不做:将 catch (Exception e) {} 更改为 catch (Exception e) {e.printStackTrace();}
  • “我的猜测是程序抛出异常。请发布它们。”
  • Edit 帖子并向其添加基本信息,而不是作为 cmets。当你在它时,标记引发异常的行,以便我们知道它是哪一个。 (RadioQuestion.java:62)
  • 是的,我将 catch (Exception e) {} 更改为 catch (Exception e) {e.printStackTrace();} ) 。发生错误。我在上面的问题中写过它们。
  • 您没有标记引发异常的行。我假设是这个:ImageIO.read(new File("‪‪‪C:\Users\syuye\eclipse-workspace\test\src\test"));,它看起来像一个错误的路径和图像名称。运行我的答案中的代码并更改它以显示 您的图像。

标签: java image swing


【解决方案1】:

为了使帮助更容易,请始终发布 mcve ,如以下示例。 请注意,它仅包含重现问题所需的最少代码(或在本例中为解决方案)。它是为了展示您的应用程序。
它使用公开可用的资源,因此可以复制和调用:

import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class RadioQuestion extends JPanel{

    private static final String bug = "https://upload.wikimedia.org/wikipedia/commons/3/3f/Crystal_Project_bug.png";

    public static void main(String args[]){
         JFrame frame=new JFrame("Image Test");
         frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
         frame.add(new RadioQuestion());
         frame.pack();
         frame.setVisible(true);
    }

    public RadioQuestion(){

        try{
            BufferedImage myPicture = ImageIO.read(new URL(bug));
            JLabel picLabel = new JLabel(new ImageIcon(myPicture));
            add(picLabel);
        } catch (Exception e) {e.printStackTrace();}
    }
}

现在使用此工作代码,并尝试将其与您的图像一起使用,以轻松找出问题所在。
旁注:永远不要通过catch (Exception e) {} 静音异常。

【讨论】:

  • 我怀疑 OP 通过尝试通过 File 而不是 URL 加载图像会面临更多问题(但这不是直接的问题)。不过,总的来说,这是个好建议。它应该让他们 90% 的“工作”。小提示:DYK 在this Q&A中有多种图片可以热链接?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
相关资源
最近更新 更多