Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class quiz extends JFrame{
- // setting up the variables for the GUI items
- private JTextField _ans1TF = new JTextField(7); // text field for Q1
- private JLabel _result = new JLabel(""); // a label to display the final result
- private JButton submitBtn = new JButton("Submit"); //a button to submit the answers
- public quiz() {
- JFrame frame = new JFrame("Quiz"); // defining a new frame for the window.
- frame.setLayout(new GridLayout(0, 3)); //using a Grid layout 0 rows 3 columns
- //adding items to the frame, when the columns in a row are full then it shall move onto the next row.
- frame.add(new JLabel("CS QUIZ"));//row 1
- frame.add(new JLabel(""));//row 1
- frame.add(new JLabel(""));//row 1
- frame.add(new JLabel("1. How many bits in a byte?"));//row 2
- frame.add(_ans1TF);//row 2
- frame.add(_result);//row 2
- //-----add more questions here...
- //-----------------------
- frame.add(new JLabel(""));//final row
- frame.add(submitBtn);//final row
- frame.pack();
- frame.setVisible(true);
- //.addActionListener links the button to the SubmitButton class, that will check the answers
- //when the submit button is clicked
- submitBtn.addActionListener(new SubmitBtnListener());
- _ans1TF.addActionListener(new SubmitBtnListener());
- }
- //code that runs when the button is clicked
- class SubmitBtnListener implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- String a1Str = _ans1TF.getText();
- if (a1Str.equals("8")){
- _result.setText("✓");//changes the result label to ✓ if the answer is correct
- } else{
- _result.setText("X");//changes the result label to X if the answer is incorrect
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment