Results 1 to 11 of 11

Thread: Help with quiz

  1. #1
    khanzaman is offline Member
    Join Date
    Jan 2009
    Posts
    8
    Rep Power
    0

    Default Help with quiz

    I have a problem with my quiz its about adding the score, i have radiobutton in each question but when i add an action that states if they are right it adds one to the variable score and one to the answer so like this:


    Java Code:
    class quiz extends JFrame implements ActionListener
    {
        //Score
       int score=0;
       int question=0;
        //question and answer
       String [] Q= {"QUESTION 1:What was the number one movie in the box office in 2008?"
       String [] A= {"India Jones and the Kingdom of the Crystal Skull","The Dark Knight"
    
    (then where the Jcomponents are added)
    ......................
    
    (then where question 1 method start)
    ....the frame then
    
    frame1_radio1=new JRadioButton(A[0]);//add Jradiobutton 1 to frame2(JFrame)
            frame1_radio1.setActionCommand("1");//adds an action to the radio button
            frame1_radio1.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio1.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio1.setBackground(Color.black);//sets a background colour of radiobutton
       
        frame1_radio2=new JRadioButton(A[1]);//add Jradiobutton 2 to frame2(JFrame)
            frame1_radio2.setActionCommand("2");//adds an action to the radio button
            frame1_radio2.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio2.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio2.setBackground(Color.black);//sets a background colour of radiobutton
    
        frame1_radio3=new JRadioButton(A[2]);//add Jradiobutton 3 to frame2(JFrame)
            frame1_radio3.setActionCommand("3");//adds an action to the radio button
            frame1_radio3.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio3.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio3.setBackground(Color.black);//sets a background colour of radiobutton
       
        frame1_radio4=new JRadioButton(A[3]);//add Jradiobutton 4 to frame2(JFrame)
            frame1_radio4.setActionCommand("4");//adds an action to the radio button
            frame1_radio4.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio4.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio4.setBackground(Color.black);//sets a background colour of button
    
    
    (then in the actionperformed method)
    
    //Question 1(method) {
        if(evt.getActionCommand().equals("2"))//if the action equals 2 then
        {//start if
            score++;//adds one to the score
            question++;//adds one to the question
        }//ends if
        else if (evt.getActionCommand().equals("1"+"3"+"4"))//if the action is equal to 1,3,4
        {//start if
            question++;//adds one to the question
        }//ends if
       
    }


    but when the score and answer are printed out in a new frame it says 0/0(score/answer).

    only thing i could think of is that it is resetting the score and answer to 0 after every frame with a question.

    does anyone know how to fix this problem
    ty

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    What is the event that causes the score to be tallied? Is it when the press a JRadioButton? Or do they press their JRadioButtons, and then press a JButton and that causes the score to be tallied? It's important as you may not be wanting to use the actionCommand to tally the score.

  3. #3
    khanzaman is offline Member
    Join Date
    Jan 2009
    Posts
    8
    Rep Power
    0

    Default

    each jradio button has an action command set to it like in my code u can see the first question has "1","2","3","4" set to each radio button but i dont rly know what it doing but the score has to be ressetting because when printed out it shows 0 set to the score. the score is tallied actually i think the action is set to when the radio button is clicked but i should make it when the raidobutton and the 'next question' button is clicked but u cant do if(evt.getActionCommand().equals("2"))&&(evt.getAc tionCommand().equals("next question")) and how am i supposed to fix the tallied score??

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    If you want to get the radiobutton selection but not on a radiobutton click, then use the ButtonGroup object that you've added the radiobuttons to.

    ButtonGroup#getSelection() returns the ButtonModel for the selected jradiobutton (or null if none selected). You can get the actionCommand from this model via the getActionCommand method and that will likely give you the information that you need.

  5. #5
    khanzaman is offline Member
    Join Date
    Jan 2009
    Posts
    8
    Rep Power
    0

    Default

    i kind of dont get it but do u have an example u can show me?

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Here's an example. Remember that with JRadioButtons, unlike standard JButtons you should explicitly set the actionCommand via setActionCommand:
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.ButtonGroup;
    import javax.swing.ButtonModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    
    public class RadioBtnSelection
    {
      private static void createAndShowUI()
      {
        String[] colors = 
        {
          "Red", "White", "Blue", "Orange", "Green"
        };
        
        JPanel radioPanel = new JPanel(new GridLayout(1, 0, 10, 10));
        
        // this button group will hold the selected button model
        final ButtonGroup buttongroup = new ButtonGroup();
        
        for (int i = 0; i < colors.length; i++)
        {
          // create a bunch of radiobuttons with the text and action command both from the 
          // colors String array above
          JRadioButton radioBtn = new JRadioButton(colors[i]);
          
          // unlike a JButton you should explicitly set the action command
          // of the JRadioButton
          radioBtn.setActionCommand(colors[i]); 
          
          radioPanel.add(radioBtn); // add to jpanel so it's visible
          buttongroup.add(radioBtn); // add to button group so it's selectable
        }
        
        JButton getSelectionBtn = new JButton("Get Selection");
    
        // add the action listener to this get selection button, *not* to the radio buttons
        getSelectionBtn.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
            // use the button group to get the selected button's button model
            ButtonModel model = buttongroup.getSelection();
            if (model != null)
            {
              // and use the model to get the actionCommand that we set up above
              System.out.println("Color selected: " + model.getActionCommand());
            }
            else
            {
              System.out.println("No Color selected");
            }
          }
        });
        
        JFrame frame = new JFrame("RadioBtnSelection");
        frame.getContentPane().add(radioPanel, BorderLayout.CENTER);
        frame.getContentPane().add(getSelectionBtn, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  7. #7
    khanzaman is offline Member
    Join Date
    Jan 2009
    Posts
    8
    Rep Power
    0

    Default

    tytytytytytytytytytytytytytytytytytytytytyty i have been going at this all weekend thank you

  8. #8
    khanzaman is offline Member
    Join Date
    Jan 2009
    Posts
    8
    Rep Power
    0

    Default

    but wait where will i put the radio buttons action command so it only adds 1 to the score to the correspond radiobutton

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I really shouldn't post this, but this was my "proof-of-concept" app that I created for this question.
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.ButtonModel;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.SwingConstants;
    
    public class QuizGUI
    {
      private JPanel mainPanel = new JPanel();
      private Question[] questions =
      {
        new Question("How many months in a year?", "12", new String[]
        {
          "1", "Several", "100", "Heck if I know?"
        }),
        new Question("Who was buried in Grant's Tomb?", "Grant", new String[]
        {
          "Washington", "Jefferson", "Lincoln", "Mickey Mouse"
        }),
        new Question("What's the air-speed velocity of a fully ladden swallow",
            "African or European?", new String[]
            {
              "100 mi/hr", "25 mi/hr", "50 mi/hr", "-10 mi/hr"
            }),
        new Question("What color was Washington's white horse?", "White",
            new String[]
            {
              "Blue", "Brown", "Chartreuse", "Mauve"
            })
      };
      private QuestionGUI[] questionGuis = new QuestionGUI[questions.length];
    
      public QuizGUI()
      {
        JPanel questionPanel = new JPanel(new GridLayout(0, 1, 0, 10));
        for (int i = 0; i < questionGuis.length; i++)
        {
          questionGuis[i] = new QuestionGUI(questions[i]);
          JComponent comp = questionGuis[i].getComponent();
          comp.setBorder(BorderFactory.createEtchedBorder());
          questionPanel.add(comp);
        }
        
        
        JButton checkAnswersBtn = new JButton("CheckAnswers");
        checkAnswersBtn.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
            int score = 0;
            for (QuestionGUI quest : questionGuis)
            {
              if (quest.isSelectionCorrect())
              {
                score++;
              }
              else
              {
                System.out.println("For the question: \"" + quest.getQuestion().getQuestion() + "\",");
                System.out.println("\"" + quest.getSelectedString() + "\" is the wrong answer");
                System.out.println("The correct answer is: \"" + quest.getQuestion().getCorrectAnswer() + "\"");
              }
            }
            System.out.println("Score: " + score);
          }
        });
        JPanel btnPanel = new JPanel();
        btnPanel.add(checkAnswersBtn);
    
        int ebGap = 10;
        mainPanel.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(questionPanel, BorderLayout.CENTER);
        mainPanel.add(btnPanel, BorderLayout.SOUTH);
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
    
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("Quiz");
        frame.getContentPane().add(new QuizGUI().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }
    
    class QuestionGUI
    {
      private JPanel mainPanel = new JPanel();
      private Question question;
      private ButtonGroup buttonGrp = new ButtonGroup();
    
      public QuestionGUI(Question question)
      {
        this.question = question;
        
        JPanel radioPanel = new JPanel(new GridLayout(1, 0, 10, 0));
        for (String str : question.getAnswers())
        {
          JRadioButton rButton = new JRadioButton(str);
          rButton.setActionCommand(str);
          radioPanel.add(rButton);
          buttonGrp.add(rButton);
        }
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.add(new JLabel(question.getQuestion(), SwingConstants.LEFT), 
            BorderLayout.NORTH);
        mainPanel.add(radioPanel, BorderLayout.CENTER);
      }
      
      public Question getQuestion()
      {
        return question;
      }
      
      public String getSelectedString()
      {
        ButtonModel model = buttonGrp.getSelection();
        if (model != null)
        {
          return model.getActionCommand();
        }
        else
          return null;
      }
      
      public boolean isSelectionCorrect()
      {
        ButtonModel model = buttonGrp.getSelection();
        if (model != null)
        {
          return question.isCorrect(model.getActionCommand());
        }
        return false;
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
    }
    
    class Question
    {
      private String question;
      private String answer;
      private List<String> answers = new ArrayList<String>();
      
      public Question(String q, String answer, String[] badAnswers)
      {
        question = q;
        this.answer = answer;
        for (String string : badAnswers)
        {
          answers.add(string);
        }
        answers.add(answer);
        Collections.shuffle(answers);
      }
      
      public String getQuestion()
      {
        return question;
      }
      
      public String[] getAnswers()
      {
        return answers.toArray(new String[0]);
      }
      
      public String getCorrectAnswer()
      {
        return answer;
      }
      
      public boolean isCorrect(String selection)
      {
        return answer.equals(selection);
      }
    }

  10. #10
    khanzaman is offline Member
    Join Date
    Jan 2009
    Posts
    8
    Rep Power
    0

    Default

    your program is confusing

    mine:

    Java Code:
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    
    
    class quiz extends JFrame implements ActionListener
    {
        //Score
       int score=0;
       int question=0;
        //question and answer
       String [] Q= {"QUESTION 1:What was the number one movie in the box office in 2008?"
       String [] A= {"India Jones and the Kingdom of the Crystal Skull","The Dark Knight","Kung Fu Panda","Hancock" 
     
      
       public void Question1()
      {
          
        frame1=new JFrame("Question #1");//adds a Jframe
            frame1.setVisible(true);//sets the frame to visible
            frame1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );//sets the Jframe to the default close which is to exit on close
            frame1.getContentPane().setBackground( Color.gray );//sets the background of the frame
            frame1.setSize(800,500);//sets the size of the frame
            frame1.setLocationRelativeTo(null);//when runned sets the frame to start in the middle of the screen
            frame1.setResizable(false);//sets the frame so it cannot be modified
      
        frame1panel1=new JPanel();//adds a Jpanel
            frame1panel1.setOpaque(false);//sets the panel not to change to default background and stay the normal frames background
            frame1panel1.setLayout(new BoxLayout(frame1panel1, BoxLayout.PAGE_AXIS));//sets the layour and creates a new box layout for the panel and sets to page_axis(top to bottom)
            frame1panel1.setBorder(BorderFactory.createEmptyBorder(80,0,0,0));//sets the border of the panel,first creates an empty border then sets the location
        
        frame1panel2=new JPanel();//adds a Jpanel
            frame1panel2.setOpaque(false);//sets the panel not to change to default background and stay the normal frames background
            frame1panel2.setLayout(new BoxLayout(frame1panel2, BoxLayout.PAGE_AXIS));//sets the layour and creates a new box layout for the panel and sets to page_axis(top to bottom)
            frame1panel2.setBorder(BorderFactory.createEmptyBorder(300,0,0,0));//sets the border of the panel,first creates an empty border then sets the location
        
        frame1panel3=new JPanel();//adds a Jpanel
            frame1panel3.setOpaque(false);//sets the panel not to change to default background and stay the normal frames background
            frame1panel3.setLayout(new BoxLayout(frame1panel3, BoxLayout.PAGE_AXIS));//sets the layour and creates a new box layout for the panel and sets to page_axis(top to bottom)
            frame1panel3.setBorder(BorderFactory.createEmptyBorder(300,0,0,0));//sets the border of the panel,first creates an empty border then sets the location
        
        frame1panel4=new JPanel();//adds a Jpanel
            frame1panel4.setOpaque(false);//sets the panel not to change to default background and stay the normal frames background
            frame1panel4.setLayout(new BoxLayout(frame1panel4, BoxLayout.PAGE_AXIS));//sets the layour and creates a new box layout for the panel and sets to page_axis(top to bottom)
            frame1panel4.setBorder(BorderFactory.createEmptyBorder(80,0,0,0));//sets the border of the panel,first creates an empty border then sets the location
        
        frame1label=new JLabel(Q[0]);
            frame1label.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1label.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1label.setBackground(Color.black);//sets a background colour of radiobutton
        
        frame1_radio1=new JRadioButton(A[0]);//add Jradiobutton 1 to frame2(JFrame)
            frame1_radio1.setActionCommand("1");//adds an action to the radio button
            frame1_radio1.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio1.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio1.setBackground(Color.black);//sets a background colour of radiobutton
        
        frame1_radio2=new JRadioButton(A[1]);//add Jradiobutton 2 to frame2(JFrame)
            frame1_radio2.setActionCommand("2");//adds an action to the radio button
            frame1_radio2.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio2.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio2.setBackground(Color.black);//sets a background colour of radiobutton
    
        frame1_radio3=new JRadioButton(A[2]);//add Jradiobutton 3 to frame2(JFrame)
            frame1_radio3.setActionCommand("3");//adds an action to the radio button
            frame1_radio3.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio3.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio3.setBackground(Color.black);//sets a background colour of radiobutton
       
        frame1_radio4=new JRadioButton(A[3]);//add Jradiobutton 4 to frame2(JFrame)
            frame1_radio4.setActionCommand("4");//adds an action to the radio button
            frame1_radio4.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
            frame1_radio4.setForeground(Color.white);//sets the foreground(text)colour to radiobutton
            frame1_radio4.setBackground(Color.black);//sets a background colour of button
       
        frame1_buttongroup1=new ButtonGroup();//add a buttongroup to frame2(JFrame)
           
       
        frame1_menu_button= new JButton("Back To Menu");//add button to frame2(JFrame)
            frame1_menu_button.setActionCommand("Back To Menu1");
            frame1_menu_button.addActionListener(this);//adds an action to button
            frame1_menu_button.setForeground(Color.white);//sets the foreground(text)colour to button
            frame1_menu_button.setBackground(Color.black);//sets a background colour of the button
            frame1_menu_button.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
        
        frame1button= new JButton("Next Question>>>>");//add button to frame2(JFrame)
            frame1button.setActionCommand("Next Question>>>>1");//sets an action for the button
            frame1button.addActionListener(this);//adds an action to button
            frame1button.setForeground(Color.white);//sets the foreground(text)colour to button
            frame1button.setBackground(Color.black);//sets a background colour of the button
            frame1button.setFont(new Font("Times New Roman",Font.PLAIN,18));//creates a Font for the radiobutton and sets it to radiobutton by the (name of font,style,size)
        
                    frame1_buttongroup1.add(frame1_radio1);//adds the radiobutton to the button group
                    frame1_buttongroup1.add(frame1_radio2);//adds the radiobutton to the button group
                    frame1_buttongroup1.add(frame1_radio3);//adds the radiobutton to the button group
                    frame1_buttongroup1.add(frame1_radio4);//adds the radiobutton to the button group
               
                    frame1panel1.add(frame1_radio1);//adds the radio button to the panel
                    frame1panel1.add(frame1_radio2);//adds the radio button to the panel
                    frame1panel1.add(frame1_radio3);//adds the radio button to the panel
                    frame1panel1.add(frame1_radio4);//adds the radio button to the panel
                    frame1panel2.add(frame1_menu_button);//adds the button
                    frame1panel3.add(frame1button);//adds the button to the panel
                    frame1panel4.add(frame1label);//adds the label to the panel
               frame1.add(frame1panel1,BorderLayout.CENTER);//adds the panel to the frame and sets a borderlayout
               frame1.add(frame1panel2,BorderLayout.WEST);//adds the panel to the frame and sets a borderlayout
               frame1.add(frame1panel3,BorderLayout.EAST);//adds the panel to the frame and sets a borderlayout
               frame1.add(frame1panel4,BorderLayout.PAGE_START);//adds the label to the frame and sets a borderlayout
       }
    
     public void actionPerformed( ActionEvent evt)
      {
        //Question 1(method) {
        ButtonModel model = frame1_buttongroup1.getSelection();
        if (model != null)
            {
              score++;
              question++;
            }
    what would i have to do to set it to one jradiobutton??

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    Unnecessarily cross posted.
    Swing - help with quiz score

    > your program is confusing
    You think yours isn't? A class with a name starting with a lowercase letter that extends JFrame and holds a (separate) instance of JFrame? Variable names like frame1_buttongroup1, frame1panel3?

    Learn Swing, you can't go through life using code generators.

    db

Similar Threads

  1. Quiz Time
    By rjuyal in forum Advanced Java
    Replies: 1092
    Last Post: 06-23-2012, 09:55 AM
  2. Help pls with a quiz
    By saytri in forum New To Java
    Replies: 3
    Last Post: 12-23-2007, 07:09 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •