将JDialog转换为Jframe / JPanel

时间:2015-06-22 03:50:04

标签: java swing jframe jpanel jdialog

所以我有以下代码来制作测验程序。我正在使用的代码扩展了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 [] possibleanswer和字符串correctanswer以显示系统知道并匹配正确的答案。这是我更新的代码

谢谢

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

        }

    }
 }

1 个答案:

答案 0 :(得分:3)

  

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

欢迎来到一个奇妙的世界,为什么你不应该从顶级容器扩展(或至少一个原因)

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

  • setModal(true);在面板上有点无意义,所以你可以摆脱它
  • getContentPane(),面板没有JRootPane,因此它没有内容窗格。您可以使用this代替
  • dispose。嗯,面板不是一个窗口,所以它不能被处理掉。&#34; 本身。我个人会用某种Observer Pattern来替换它,当测验的状态发生变化时(例如它已经完成)会提供通知,这样调用者就可以按照他们想要的方式处理它。关键是,不要假设人们可能会如何使用您的组件
  • pack,好吧,这和其他人一样,所以你可以摆脱它。
  • setVisible,默认情况下,Swing组件是可见的,所以它可能有点无意义。

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

  

因为当我尝试运行代码时,窗口都很小,我似乎无法将完成的按钮移动到&#34; Next&#34;按钮

这是一个布局问题。在您的情况下,我会使用复合布局,可能使用FlowLayout作为按钮,使用BorderLayout作为&#34;问题&#34;和按钮面板(在SOUTH位置)。

顺便提一下,您应该使用CardLayout来显示问题,我presented in this surprisingly similar question

  

另外如果我想让这个问题变得随机怎么做呢?

Collections.shuffle(questions);可能是我能想到的最简单的解决方案。一旦你打电话,List将被随机改组。

  

所以我只是编辑代码我想知道你是否可以发表一些评论如何解决它。谢谢

嗯,这是原始答案的背景......

  • 看看Collections Trail,您使用的是List,就好像它是一个阵列一样,现在它们是如何工作的。
  • QuestionJPanel)没有实施ActionListener因此next.addActionListener(this);无法正常工作
  • 您忘记将aPanel.add(responses[i]);换成循环并创建JRadioButton,这些都应添加到同一ButtonGroup
  • Choices in Question从未分配过值,并会生成NullPointerException。我担心直接暴露MultipleChoice,并会亲自使用interface提供可以针对该类执行的内容的合同
  • 添加&#34;可能&#34;答案,您还需要包含正确的答案。我添加List JRadioButton Collection.shuffle,每个可能答案一个,正确答案一个,我会使用List将此Question改组为一些随机方式,然后将按钮添加到printf("%d\n", (char) (246) ); 面板