Advertisement
mrScarlett

Quiz Code GUI

May 23rd, 2017
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. import java.awt.*;
  2. import javax.swing.*;
  3. import java.awt.event.*;
  4.  
  5. public class quiz extends JFrame{
  6.  
  7.   // setting up the variables for the GUI items
  8.   private JTextField _ans1TF = new JTextField(7); // text field for Q1
  9.   private JLabel _result = new JLabel(""); // a label to display the final result
  10.   private JButton submitBtn = new JButton("Submit"); //a button to submit the answers
  11.  
  12.   public quiz() {
  13.     JFrame frame = new JFrame("Quiz"); // defining a new frame for the window.
  14.    
  15.    
  16.     frame.setLayout(new GridLayout(0, 3)); //using a Grid layout 0 rows 3 columns
  17.    
  18.     //adding items to the frame, when the columns in a row are full then it shall move onto the next row.
  19.     frame.add(new JLabel("CS QUIZ"));//row 1
  20.     frame.add(new JLabel(""));//row 1
  21.     frame.add(new JLabel(""));//row 1
  22.    
  23.     frame.add(new JLabel("1. How many bits in a byte?"));//row 2
  24.     frame.add(_ans1TF);//row 2
  25.     frame.add(_result);//row 2
  26.    
  27.     //-----add more questions here...
  28.    
  29.    //-----------------------
  30.    frame.add(new JLabel(""));//final row
  31.    frame.add(submitBtn);//final row
  32.    
  33.    
  34.    frame.pack();
  35.    frame.setVisible(true);
  36.    
  37.    //.addActionListener links the button to the SubmitButton class, that will check the answers
  38.    //when the submit button is clicked
  39.    submitBtn.addActionListener(new SubmitBtnListener());
  40.    _ans1TF.addActionListener(new SubmitBtnListener());
  41.   }
  42.  
  43.   //code that runs when the button is clicked
  44.   class SubmitBtnListener implements ActionListener {        
  45.         public void actionPerformed(ActionEvent e) {
  46.             String a1Str = _ans1TF.getText();
  47.             if (a1Str.equals("8")){
  48.                 _result.setText("✓");//changes the result label to ✓ if the answer is correct
  49.             } else{
  50.                 _result.setText("X");//changes the result label to X if the answer is incorrect
  51.             }
  52.            
  53.         }
  54.     }
  55.  
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement