0% found this document useful (0 votes)
9 views14 pages

week_8java

The document describes a Java Swing application for a Quiz Form that includes various question types such as radio buttons, checkboxes, text fields, and text areas. It features a submit button that calculates the total score based on user responses and displays the result. The application is structured with a JFrame and JPanel to organize the layout and components.

Uploaded by

esupmet2426
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views14 pages

week_8java

The document describes a Java Swing application for a Quiz Form that includes various question types such as radio buttons, checkboxes, text fields, and text areas. It features a submit button that calculates the total score based on user responses and displays the result. The application is structured with a JFrame and JPanel to organize the layout and components.

Uploaded by

esupmet2426
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

import javax.swing.

*;
import java.awt.*;
import java.awt.event.*;

public class QuizForm {


private JFrame frame;
private JPanel panel;
private JLabel question1Label;
private JRadioButton option1Radio;
private JRadioButton option2Radio;
private JRadioButton option3Radio;
private ButtonGroup optionGroup;
private JLabel correctAnswerLabel;
private JCheckBox checkBox1;
private JCheckBox checkBox2;
private JCheckBox checkBox3;
private JTextField textField;
private JTextArea textArea;
private JButton submitButton;

private int totalScore;

public QuizForm() {
frame = new JFrame("Quiz Form");
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

// Question 1: Radio buttons


question1Label = new JLabel("What is the capital of France?");
panel.add(question1Label);

option1Radio = new JRadioButton("Paris");


option2Radio = new JRadioButton("London");
option3Radio = new JRadioButton("Berlin");

optionGroup = new ButtonGroup();


optionGroup.add(option1Radio);
optionGroup.add(option2Radio);
optionGroup.add(option3Radio);

panel.add(option1Radio);
panel.add(option2Radio);
panel.add(option3Radio);

// Question 2: Check boxes


JLabel question2Label = new JLabel("What are the colors of the French
flag?");
panel.add(question2Label);

checkBox1 = new JCheckBox("Blue");


checkBox2 = new JCheckBox("White");
checkBox3 = new JCheckBox("Red");

panel.add(checkBox1);
panel.add(checkBox2);
panel.add(checkBox3);

// Question 3: Text field


JLabel question3Label = new JLabel("What is the name of the famous
French painter?");
panel.add(question3Label);

textField = new JTextField(20);


panel.add(textField);

// Question 4: Text area


JLabel question4Label = new JLabel("Write a short essay about the
Eiffel Tower:");
panel.add(question4Label);

textArea = new JTextArea(5, 20);


panel.add(textArea);

// Submit button
submitButton = new JButton("Submit");
submitButton.addActionListener(new SubmitButtonListener());
panel.add(submitButton);

correctAnswerLabel = new JLabel("Correct answers will be displayed


here.");
panel.add(correctAnswerLabel);

frame.add(panel);
frame.pack();
frame.setVisible(true);
}

private class SubmitButtonListener implements ActionListener {


public void actionPerformed(ActionEvent e) {
findTotalScore();
}
}

public void findTotalScore() {


totalScore = 0;

// Question 1: Radio buttons


if (option1Radio.isSelected()) {
totalScore++;
}

// Question 2: Check boxes


if (checkBox1.isSelected() && checkBox2.isSelected() &&
checkBox3.isSelected()) {
totalScore++;
}

// Question 3: Text field


if (textField.getText().trim().equalsIgnoreCase("Claude Monet")) {
totalScore++;
}
// Question 4: Text area
if (textArea.getText().trim().contains("Eiffel Tower")) {
totalScore++;
}

correctAnswerLabel.setText("Your total score is " + totalScore + " out


of 4.");
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new QuizForm();
}
});
}
}

output:

2.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame implements ActionListener {


// Components of the calculator
private JTextField display;
private JButton[] numberButtons;
private JButton[] functionButtons;
private JButton addButton, subButton, mulButton, divButton;
private JButton equalButton, clearButton, dotButton;

// Variables for calculations


private double num1 = 0, num2 = 0, result = 0;
private char operator;

// Constructor for Calculator


public Calculator() {
// Set window title
setTitle("Calculator");
// Set default size of window
setSize(300, 400);
// Set default location of window
setLocationRelativeTo(null);
// Set window to be not resizable
setResizable(false);
// Set default close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create display field


display = new JTextField();
// Set display field to be non-editable
display.setEditable(false);
// Set display field to be centered
display.setHorizontalAlignment(JTextField.RIGHT);
// Add display field to the calculator
add(display, BorderLayout.NORTH);

// Create number buttons


numberButtons = new JButton[10];
JPanel numberPanel = new JPanel(new GridLayout(4, 3, 5, 5));
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
numberPanel.add(numberButtons[i]);
}
// Create dot button
dotButton = new JButton(".");
dotButton.addActionListener(this);
numberPanel.add(dotButton);
// Add number panel to the calculator
add(numberPanel, BorderLayout.CENTER);

// Create function buttons


functionButtons = new JButton[4];
JPanel functionPanel = new JPanel(new GridLayout(4, 1, 5, 5));
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
functionButtons[0] = addButton;
functionButtons[1] = subButton;
functionButtons[2] = mulButton;
functionButtons[3] = divButton;
for (JButton button : functionButtons) {
button.addActionListener(this);
functionPanel.add(button);
}
// Add function panel to the calculator
add(functionPanel, BorderLayout.EAST);

// Create equal and clear buttons


equalButton = new JButton("=");
clearButton = new JButton("C");
equalButton.addActionListener(this);
clearButton.addActionListener(this);
JPanel equalClearPanel = new JPanel(new GridLayout(1, 2, 5, 5));
equalClearPanel.add(equalButton);
equalClearPanel.add(clearButton);
// Add equal and clear panel to the calculator
add(equalClearPanel, BorderLayout.SOUTH);

// Make the calculator visible


setVisible(true);
}

// Method to handle button clicks


public void actionPerformed(ActionEvent e) {
// Get the source of the event
JButton button = (JButton) e.getSource();

// Check if the button is a number button


for (int i = 0; i < 10; i++) {
if (button == numberButtons[i]) {
display.setText(display.getText() + i);
return;
}
}

// Check if the button is the dot button


if (button == dotButton) {
if (!display.getText().contains(".")) {
display.setText(display.getText() + ".");
}
return;
}

// Check if the button is an operator button


if (button == addButton) {
operator = '+';
} else if (button == subButton) {
operator = '-';
} else if (button == mulButton) {
operator = '*';
} else if (button == divButton) {
operator = '/';
}

// Check if the button is the equal button


if (button == equalButton) {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
display.setText(String.valueOf(result));
num1 = 0;
num2 = 0;
return;
}

// Check if the button is the clear button


if (button == clearButton) {
display.setText("");
num1 = 0;
num2 = 0;
return;
}

// Set num1 to the current display value


num1 = Double.parseDouble(display.getText());
// Clear the display
display.setText("");
}

// Main method to start the calculator


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

output:
3.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GoogleAccountRegistration extends JFrame implements


ActionListener {
private JTextField firstNameField, lastNameField, usernameField,
phoneField, recoveryEmailField, dayField, yearField, genderField;
private JPasswordField passwordField, confirmPasswordField;
private JComboBox monthBox;
private JButton createAccountButton, resetButton, cancelButton;

public GoogleAccountRegistration() {
super("Create Google Account");
setSize(400, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(10, 2));
setLocationRelativeTo(null);

// Labels and Text Fields


JLabel firstNameLabel = new JLabel("First Name:");
firstNameField = new JTextField();
JLabel lastNameLabel = new JLabel("Last Name:");
lastNameField = new JTextField();
JLabel usernameLabel = new JLabel("Username:");
usernameField = new JTextField();
JLabel passwordLabel = new JLabel("Password:");
passwordField = new JPasswordField();
JLabel confirmPasswordLabel = new JLabel("Confirm Password:");
confirmPasswordField = new JPasswordField();
JLabel phoneLabel = new JLabel("Phone Number:");
phoneField = new JTextField();
JLabel recoveryEmailLabel = new JLabel("Recovery Email:");
recoveryEmailField = new JTextField();
JLabel monthLabel = new JLabel("Month:");
String[] months = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"};
monthBox = new JComboBox(months);
JLabel dayLabel = new JLabel("Day:");
dayField = new JTextField();
JLabel yearLabel = new JLabel("Year:");
yearField = new JTextField();
JLabel genderLabel = new JLabel("Gender:");
genderField = new JTextField();

// Buttons
createAccountButton = new JButton("Create Account");
createAccountButton.addActionListener(this);
resetButton = new JButton("Reset");
resetButton.addActionListener(this);
cancelButton = new JButton(" Cancel");
cancelButton.addActionListener(this);

// Add components to the frame


add(firstNameLabel);
add(firstNameField);
add(lastNameLabel);
add(lastNameField);
add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(confirmPasswordLabel);
add(confirmPasswordField);
add(phoneLabel);
add(phoneField);
add(recoveryEmailLabel);
add(recoveryEmailField);
add(monthLabel);
add(monthBox);
add(dayLabel);
add(dayField);
add(yearLabel);
add(yearField);
add(genderLabel);
add(genderField);
add(createAccountButton);
add(resetButton);
add(cancelButton);

setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == createAccountButton) {
// Validate input fields
if (validateFields()) {
// Create account logic here
JOptionPane.showMessageDialog(this, "Account created
successfully!");
}
} else if (e.getSource() == resetButton) {
// Reset fields
resetFields();
} else if (e.getSource() == cancelButton) {
// Close the window
dispose();
}
}

private boolean validateFields() {


// Validate first name
if (firstNameField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "First name is required!");
return false;
}

// Validate last name


if (lastNameField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Last name is required!");
return false;
}

// Validate username
if (usernameField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Username is required!");
return false;
}

// Validate password
if (passwordField.getPassword().length == 0) {
JOptionPane.showMessageDialog(this, "Password is required!");
return false;
}

// Validate confirm password


if (!
String.valueOf(passwordField.getPassword()).equals(String.valueOf(confirmPassw
ordField.getPassword()))) {
JOptionPane.showMessageDialog(this, "Passwords do not match!");
return false;
}

// Validate phone number


if (phoneField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Phone number is required!");
return false;
}

// Validate recovery email


if (recoveryEmailField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Recovery email is
required!");
return false;
}

// Validate birthdate
if (dayField.getText().trim().isEmpty() ||
yearField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Birthdate is required!");
return false;
}

// Validate gender
if (genderField.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "Gender is required!");
return false;
}

// Validate phone number format


String phoneRegex = "^\\d{10}$";
Pattern phonePattern = Pattern.compile(phoneRegex);
Matcher phoneMatcher = phonePattern.matcher(phoneField.getText());
if (!phoneMatcher.matches()) {
JOptionPane.showMessageDialog(this, "Invalid phone number
format!");
return false;
}

return true;
}

private void resetFields() {


firstNameField.setText("");
lastNameField.setText("");
usernameField.setText("");
passwordField.setText("");
confirmPasswordField.setText("");
phoneField.setText("");
recoveryEmailField.setText("");
dayField.setText("");
yearField.setText("");
genderField.setText("");
}

public static void main(String[] args) {


new GoogleAccountRegistration();
}
}
output:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class QuizForm {


private JFrame frame;
private JPanel panel;
private JLabel question1Label;
private JRadioButton option1Radio;
private JRadioButton option2Radio;
private JRadioButton option3Radio;
private JRadioButton option4Radio;
private ButtonGroup optionGroup;
private JLabel correctAnswerLabel;
private JCheckBox checkBox1;
private JCheckBox checkBox2;
private JCheckBox checkBox3;
private JCheckBox checkBox4;
private JCheckBox checkBox5;

private JTextField textField;


private JTextArea textArea;
private JButton submitButton;

private int totalScore;

public QuizForm() {
frame = new JFrame("Quiz Form");
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

// Question 1: Radio buttons


question1Label = new JLabel("Which pacakge is used for swing
components?");
panel.add(question1Label);

option1Radio = new JRadioButton("java.awt");


option2Radio = new JRadioButton("javax.swing");
option3Radio = new JRadioButton("javafx");
option4Radio = new JRadioButton("java.util");

optionGroup = new ButtonGroup();


optionGroup.add(option1Radio);
optionGroup.add(option2Radio);
optionGroup.add(option3Radio);
optionGroup.add(option4Radio);

panel.add(option1Radio);
panel.add(option2Radio);
panel.add(option3Radio);
panel.add(option4Radio);

// Question 2: Check boxes


JLabel question2Label = new JLabel("Which of the following are layout
manners?");
panel.add(question2Label);

checkBox1 = new JCheckBox("border layout");


checkBox2 = new JCheckBox("flow layout");
checkBox3 = new JCheckBox("grid layout");
checkBox4 = new JCheckBox("flow layout");
checkBox5 = new JCheckBox("grid layout");

panel.add(checkBox1);
panel.add(checkBox2);
panel.add(checkBox3);
panel.add(checkBox4);
panel.add(checkBox5);
// Question 3: Text field
JLabel question3Label = new JLabel("What is the name of the famous
French painter?");
panel.add(question3Label);

textField = new JTextField(20);


panel.add(textField);

// Question 4: Text area


JLabel question4Label = new JLabel("Write a short essay about the
Eiffel Tower:");
panel.add(question4Label);

textArea = new JTextArea(5, 20);


panel.add(textArea);

// Submit button
submitButton = new JButton("Submit");
submitButton.addActionListener(new SubmitButtonListener());
panel.add(submitButton);

correctAnswerLabel = new JLabel("Correct answers will be displayed


here.");
panel.add(correctAnswerLabel);

frame.add(panel);
frame.pack();
frame.setVisible(true);
}

private class SubmitButtonListener implements ActionListener {


public void actionPerformed(ActionEvent e) {
findTotalScore();
}
}

public void findTotalScore() {


totalScore = 0;

// Question 1: Radio buttons


if (option1Radio.isSelected()) {
totalScore++;
}

// Question 2: Check boxes


if (checkBox1.isSelected() && checkBox2.isSelected() &&
checkBox3.isSelected()) {
totalScore++;
}

// Question 3: Text field


if (textField.getText().trim().equalsIgnoreCase("Claude Monet")) {
totalScore++;
}

// Question 4: Text area


if (textArea.getText().trim().contains("Eiffel Tower")) {
totalScore++;
}

correctAnswerLabel.setText("Your total score is " + totalScore + " out


of 4.");
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new QuizForm();
}
});
}
}

You might also like