繁体   English   中英

将JDialog转换为Jframe / JPanel

[英]Converting JDialog into Jframe/JPanel

因此,我有以下代码来编写测验程序。 我正在使用的代码扩展了JDialog。 我想知道是否有一种将其转换为JPanel的方法,因为当我尝试运行代码时,窗口很小,而且似乎无法将完成的按钮移到“下一步”按钮旁边。 另外,如果我想随机回答问题,那该怎么办?

谢谢

import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.Random;
import javax.swing.JRadioButton;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MultipleChoice extends JDialog {  
int correctAns;
List<Question> questions = new ArrayList<Question>();
//asnwers
JRadioButton[] responses;
ButtonGroup group = new ButtonGroup();
//bottom
JButton next = new JButton("Next");
JButton finish = new JButton("Finish");

public MultipleChoice(){
   super();
   setModal(true);
   setLayout( new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));  //setting up boxlayout

   questions.add(new Question("Which of the following is NOT one of the 5 great lakes?",new String[]{"Lake Mead","Lake Huron","Lake Michigan","Lake Erie"}, "Lake Mead"));
   questions.add(new Question("What is the Capital of Colorado?",new String[]{"Boulder","Aspen","Denver","Cheyenne"},"Denver"));
   questions.add(new Question("Each side of a baseball diamond is 90 feet in length. How far is it around the Baseball Diamond?",new String[]{"270","360","180","390"},"360"));
   questions.add(new Question("What color do you get when you combine an equal amount of red paint with an equal amount of yellow paint?",new String[]{"Blue","Orange","Green","Pink"},"Orange"));
   questions.add(new Question("How many sides does a trapezoid have?",new String[]{"3","4","5","6"},"2"));
   questions.add(new Question("Which is a simile?",new String[]{"My sister is cute like a bunny","My mom has a manly snore","My dad is better than yours"},"My sister is cute like a bunny"));
   questions.add(new Question("Polar bears eat penquins?",new String[]{"True","False"},"True"));

  //bottom
  next.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
          setVisible(false);
        }
    });
  finish.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
          setVisible(false);
        }
    });
   }

 public int beginQuiz(){  
        int score=0;
        for (Question q : questions){
            displayQuestion(q);
            if (group.getSelection().getActionCommand().equals(q.getans())){
                score++;
            }
        }
        dispose();
        return score;
 }

 private void displayQuestion(Question q){
        getContentPane().removeAll();
        for (Enumeration buttonGroup=group.getElements(); buttonGroup.hasMoreElements(); ){
            group.remove((AbstractButton)buttonGroup.nextElement());
        }

        JLabel questionText = new JLabel(q.getquestion());
        getContentPane().add(questionText);
        for (String answer : q.getanswers()){
            JRadioButton radio = new JRadioButton(answer);
            radio.setActionCommand(answer);
            group.add(radio);
            getContentPane().add(radio);
        }
        getContentPane().add(next);
        getContentPane().add(finish);
        pack();
        setVisible(true);
    }

public static void showSummary(int score){
  JOptionPane.showMessageDialog(null,"All Done :), here are your results"+
        "\nNumber of incorrect Answers: \t"+(7-score)+
        "\nNumber of Correct Answers: \t"+(score)+
        "\nPercent Correct: \t\t"+(int)(((float)(score)/7)*100)+"%"
    );
  if (((int)(((float)(score)/7)*100))> 0.6)
         JOptionPane.showMessageDialog(null,"You Passed!");
  else {
         JOptionPane.showMessageDialog(null,"You are NOT Smarter than a 5th Grader");
       }
}

 public static void main(String[] args){
  MultipleChoice quiz = new MultipleChoice();
  int score = quiz.beginQuiz();
  showSummary(score);
 }  
}

class Question {
private String question;
private String[] answers;
private String ans;

String getquestion(){    //getter
  return question;
 }
void setquestion(String str){    //setter
   question = str;
 }
 String[] getanswers(){    //getter
  return answers;
 }
 void setanswers(String[] str2){    //setter
   answers = str2;
 }
String getans(){    //getter
  return ans;
}
void setans(String str3){    //setter
   ans = str3;
 }

public Question(String possibleQuestion ,String[] possibleAnswer , String correctAnswer){     //constructor
   question = possibleQuestion;
   answers = possibleAnswer;
   ans = correctAnswer;
 }
 } 

更新了新的修改

在我编辑并尝试将其转换为JPanel并使用建议的cardlayout后,我遇到了一些错误,似乎无法弄清楚如何获取String []可能的答案和字符串正确的答案,以使系统知道和匹配该答案。正确答案。 这是我更新的代码

谢谢

import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.Random;
import java.awt.CardLayout;
import javax.swing.JRadioButton;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MultipleChoice {  
int correctAns;
List<Question> questions = new ArrayList<Question>();
JPanel p=new JPanel();
CardLayout cards=new CardLayout();
int numQs;
int wrongs=0;
int total=0;

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

public MultipleChoice(){
  JFrame frame = new JFrame("Are you Smarter than a 5th Grader?");
  frame.setResizable(true);
  frame.setSize(500,400);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   questions.add(new Question("Which of the following is NOT one of the 5 great lakes?",new String[]{"Lake Mead","Lake Huron","Lake Michigan","Lake Erie"}, "Lake Mead"));
   questions.add(new Question("What is the Capital of Colorado?",new String[]{"Boulder","Aspen","Denver","Cheyenne"},"Denver"));
   questions.add(new Question("Each side of a baseball diamond is 90 feet in length. How far is it around the Baseball Diamond?",new String[]{"270","360","180","390"},"360"));
   questions.add(new Question("What color do you get when you combine an equal amount of red paint with an equal amount of yellow paint?",new String[]{"Blue","Orange","Green","Pink"},"Orange"));
   questions.add(new Question("How many sides does a trapezoid have?",new String[]{"3","4","5","6"},"2"));
   questions.add(new Question("Which is a simile?",new String[]{"My sister is cute like a bunny","My mom has a manly snore","My dad is better than yours"},"My sister is cute like a bunny"));
   questions.add(new Question("Polar bears eat penquins?",new String[]{"True","False"},"True"));

    p.setLayout(cards);
    numQs=questions.size();
    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);
    frame.add(p);
    frame.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)+
        "\nPercent Correct: \t\t"+(int)(((float)(total-wrongs)/total)*100)+"%"
    );
  if (((int)(((float)(total-wrongs)/total)*100))> 0.6)
         JOptionPane.showMessageDialog(null,"You Passed!");
  else {
         JOptionPane.showMessageDialog(null,"You are NOT Smarter than a 5th Grader");
       }
    System.exit(0);
   }      
 }

class Question extends JPanel {
int correctAns;
MultipleChoice Choices; 
int selected;
boolean used;
//questions
JPanel qPanel=new JPanel();
//answers
JPanel aPanel=new JPanel();
JRadioButton[] responses;
//bottom
JPanel botPanel=new JPanel();
JButton next=new JButton("Next");
JButton finish=new JButton("Finish");

private String question;
private String[] answers;
private String ans;
public Question(String possibleQuestion ,String[] possibleAnswer , String correctAnswer){     //constructor
   this.Choices=Choices;
   question = possibleQuestion;
   answers = possibleAnswer;
   ans = correctAnswer;

   setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
    //question
   qPanel.add(new JLabel(question));
   add(qPanel);
    //answer
  responses=new JRadioButton[answers.length];
     //display possible answer and answers
  aPanel.add(responses[i]);

  add(aPanel);


    //bottom
    next.addActionListener(this);
    finish.addActionListener(this);
    botPanel.add(next);
    botPanel.add(finish);
    add(botPanel);
}

public Question(String possibleQuestion ,String[] possibleAnswer){   //constructor overloading
   question = possibleQuestion;
   answers = possibleAnswer;
}

String getquestion(){    //getter
  return question;
}
void setquestion(String str){    //setter
   question = str;
}
 String[] getanswers(){    //getter
  return answers;
 }
void setanswers(String[] str2){    //setter
   answers = str2;
}
 String getans(){    //getter
  return ans;
}
void setans(String str3){    //setter
   ans = str3;
}

public void actionPerformed(ActionEvent e){
    Object src=e.getSource();
    //next button
    if(src.equals(next)){
        if(selected==correctAns){
            used=true;
            Choices.next();
        }
    }
    //finish button
    if(src.equals(finish)){
        Choices.showSummary();
    }
  }
}

新修订版因此,在创建接口并实现它之后。 我似乎无法显示问题或选项。 JButton似乎不起作用。

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

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

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

public MultipleChoice(){
  List<Question> questions = new ArrayList<>();

   questions.add(new Question("Which of the following is NOT one of the 5 great lakes?",new String[]{"Lake Mead","Lake Huron","Lake Michigan","Lake Erie"}, "Lake Mead"));
   questions.add(new Question("What is the Capital of Colorado?",new String[]{"Boulder","Aspen","Denver","Cheyenne"},"Denver"));
   questions.add(new Question("Each side of a baseball diamond is 90 feet in length. How far is it around the Baseball Diamond?",new String[]{"270","360","180","390"},"360"));
   questions.add(new Question("What color do you get when you combine an equal amount of red paint with an equal amount of yellow paint?",new String[]{"Blue","Orange","Green","Pink"},"Orange"));
   questions.add(new Question("How many sides does a trapezoid have?",new String[]{"3","4","5","6"},"2"));
   questions.add(new Question("Which is a simile?",new String[]{"My sister is cute like a bunny","My mom has a manly snore","My dad is better than yours"},"My sister is cute like a bunny"));
   questions.add(new Question("Polar bears eat penquins?",new String[]{"True","False"},"True"));

  JFrame frame = new JFrame("Are you Smarter than a 5th Grader?");
  frame.setResizable(true);
  frame.setSize(500,400);
  frame.add(new QuizPane(questions));
  frame.pack();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);

  }
 public class QuizPane extends JPanel {
    private CardLayout cardLayout;
    private int currentQuestion;
    private JButton next;
    private List<Question> question;

    private JPanel panelOfQuestions;
  public QuizPane(List<Question> question) {
        this.question = question;
        cardLayout = new CardLayout();
        panelOfQuestions = new JPanel(cardLayout);

        JButton start = new JButton("Start");
        start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentQuestion = -1;
                next();
            }
        });

        JPanel filler = new JPanel(new GridBagLayout());
        filler.add(start);
        panelOfQuestions.add(filler, "start");

        for (int index = 0; index < question.size(); index++) {
            QuestionInterface quiz = question.get(index);
            QuestionPane pane = new QuestionPane(quiz);
            panelOfQuestions.add(pane, Integer.toString(index));
        }
        panelOfQuestions.add(new JLabel("The quiz is over"), "last");
        currentQuestion = 0;
        cardLayout.show(panelOfQuestions, "start");

        setLayout(new BorderLayout());
        add(panelOfQuestions);

        JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        next = new JButton("Next");
        buttonPane.add(next);
        next.setEnabled(false);

        add(buttonPane, BorderLayout.SOUTH);

        next.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                next();
            }
        }); 
    }
    public void next(){
      if (currentQuestion >= question.size()) {
            cardLayout.show(panelOfQuestions, "last");
            next.setEnabled(false);
            // You could could loop through all the questions and tally
            // the correct answers here
          } 
      else {
            cardLayout.show(panelOfQuestions, Integer.toString(currentQuestion));
            next.setText("Next");
            next.setEnabled(true);
        }
   }

   /*public void showSummary(){   // try to get to show summary after the quiz
    JOptionPane.showMessageDialog(null,"All Done :), here are your results"+
        "\nNumber of incorrect Answers: \t"+wrongs+
        "\nNumber of Correct Answers: \t"+(total-wrongs)+
        "\nPercent Correct: \t\t"+(int)(((float)(total-wrongs)/total)*100)+"%"
    );
    if (((int)(((float)(total-wrongs)/total)*100))> 0.6)
         JOptionPane.showMessageDialog(null,"You Passed!");
    else {
         JOptionPane.showMessageDialog(null,"You are NOT Smarter than a 5th Grader");
       }
    System.exit(0);
    }*/  

  }

  public interface QuestionInterface {

    public String getquestion();

    public String[] getOptions();

    public String getAnswer();

    public String getUserResponse();

    public void setUserResponse(String response);

    public boolean isCorrect();
  }
  public class Question implements QuestionInterface {
 private String possibleQuestion;
 private String[] Options;
 public String correctAnswer;

 private String userResponse;

 public Question(String possibleQuestion ,String[] Options , String correctAnswer){     //constructor
   this.possibleQuestion = possibleQuestion;
   this.Options = Options;
   this.correctAnswer = correctAnswer;
 }

 public Question(String possibleQuestion ,String[] possibleAnswer){   //constructor overloading
   this.possibleQuestion = possibleQuestion;
   this.Options = Options;
  }

 public String getquestion(){    //getter
  return possibleQuestion;
  }

 void setquestion(String str){    //setter
   possibleQuestion = str;
  }

 public String[] getOptions(){    //getter
   return Options;
 }

 void setanswers(String[] str2){    //setter
   Options = str2;
 }

 public String getAnswer(){    //getter
    return correctAnswer;
 }

 void setans(String str3){    //setter
   correctAnswer = str3;
 }

 public String getUserResponse() {
        return userResponse;
    }

 public void setUserResponse(String response) {
        userResponse = response;
    }

 public boolean isCorrect() {
        return getAnswer().equals(getUserResponse());
    }
}
 public class QuestionPane extends JPanel {

    private QuestionInterface question;

    public QuestionPane(QuestionInterface question) {
        this.question = question;

        setLayout(new BorderLayout());

        JLabel prompt = new JLabel("<html><b>" + question.getquestion() + "</b></html>");
        prompt.setHorizontalAlignment(JLabel.LEFT);

        add(prompt, BorderLayout.NORTH);

        JPanel guesses = new JPanel(new GridBagLayout());
        guesses.setBorder(new EmptyBorder(5, 5, 5, 5));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 1;
        gbc.anchor = GridBagConstraints.WEST;

        List<String> options = new ArrayList<>(Arrays.asList(question.getOptions()));
        options.add(question.getAnswer());
        Collections.sort(options);

        ButtonGroup bg = new ButtonGroup();
        for (String option : options) {
            JRadioButton btn = new JRadioButton(option);
            bg.add(btn);

            guesses.add(btn, gbc);
        }

        add(guesses);

    }

    public QuestionInterface getQuestion() {
        return question;
    }

    public class ActionHandler implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            getQuestion().setUserResponse(e.getActionCommand());
        }

        }

    }
 }

我正在使用的代码扩展了JDialog。 我想知道是否有办法将其转换为JPanel

欢迎来到美好世界,为什么您不应该从顶级容器中扩展(或者至少是其中一个原因)

首先从JPanel而不是JDialog扩展MultipleChoice 这将产生许多编译器错误。

  • setModal(true); 在面板上没有意义,因此您可以摆脱它
  • getContentPane() ,一个面板没有JRootPane所以它没有内容窗格。 您可以改用this
  • dispose 那么,一个面板是不是一个窗口,因此它不能被“设置” 本身 我个人将其替换为某种“ 观察者模式” ,该观察者模式会在测验的状态发生变化(例如完成测验)时提供通知,以便调用者可以按照他们想要的方式进行处理。 重点是,不要对人们可能会喜欢使用您的组件的方式做出假设
  • pack ,好吧,它和其他船在同一条船上,所以您可以摆脱它。
  • setVisible ,默认情况下,Swing组件是可见的,因此可能没有意义。

知道,您所需要做的就是创建MultipleChoice面板的实例并将其添加到所需的任何容器中。

因为当我尝试运行代码时,窗口很小,而且似乎无法将完成的按钮移到“下一步”按钮旁边

这是一个布局问题。 在你的情况,我会使用复合布局,也许使用FlowLayout的按钮和一个BorderLayout ,为“问题”和按键面板(在SOUTH位置)。

顺便说一句,您可能应该使用CardLayout来显示问题,这是我在这个令人惊讶的类似问题中提出的

另外,如果我想随机回答问题,那该怎么办?

Collections.shuffle(questions); 这可能是我能想到的最简单的解决方案。 调用该List ,该List将被随机排列。

所以我只是编辑代码,我想知道您是否可以提出一些意见来解决它。 谢谢

好吧,这里有原始答案的内容...

  • 看一下Collections Trail ,您正在使用一个List ,就好像它是一个数组一样,这就是它们的工作方式。
  • QuestionJPanel )没有实现ActionListener所以next.addActionListener(this); 不上班
  • 您忘记包装aPanel.add(responses[i]); 循环并创建JRadioButton ,所有这些都应添加到同一ButtonGroup
  • Choices中的Question从未分配值,并且将生成NullPointerException 我担心直接暴露MultipleChoice ,会亲自使用一个interface ,该interface提供可针对该类执行的契约
  • 添加“可能的”答案时,还需要包括正确的答案。 我将添加构建一个JRadioButton List ,一个用于每个可能的答案,一个用于正确的答案,我将使用Collection.shuffle以某种随机的方式来随机播放此List ,然后将按钮添加到“ Question面板中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM