0% found this document useful (0 votes)
16 views10 pages

JAVA Swings

more notes on java

Uploaded by

shahbharat2609
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)
16 views10 pages

JAVA Swings

more notes on java

Uploaded by

shahbharat2609
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/ 10

ASSIGNMENT ON JAVA SWINGS

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

public class MathTest {


private JFrame frame;
private JPanel panel;
private JProgressBar progressBar;
private JButton startButton;
private JLabel titleLabel;
private int progressValue = 0;
private Timer timer;

public MathTest() {
frame = new JFrame("ProgressBar");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 500);

panel = new JPanel(new GridBagLayout());


GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(20, 20, 20, 20); // Add margins to all
sides

titleLabel = new JLabel("Hey there! Click on the start button


to start the test.");
titleLabel.setFont(new Font("Mongolian Baiti", Font.BOLD, 25));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
panel.add(titleLabel, gbc);

progressBar = new JProgressBar(0, 100);


Dimension customProgressBarSize = new Dimension(400, 20);
progressBar.setPreferredSize(customProgressBarSize);
progressBar.setStringPainted(true);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2;
panel.add(progressBar, gbc);

startButton = new JButton("Start");


startButton.setAlignmentX(Component.CENTER_ALIGNMENT);
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startButton.setEnabled(false);
progressValue = 0;
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (progressValue < 100) {
progressValue++;
progressBar.setValue(progressValue);
} else {
timer.stop();
frame.setVisible(false);
new TestPage();
}
}
});
timer.start();
}
});
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
panel.add(startButton, gbc);

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

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new MathTest());
}
}

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

public class TestPage {


private JFrame frame;
private JTextField nameField;
private JTextField phoneField;
private JTextArea aboutYouTextArea;
private JSlider ageSlider;
private JLabel ageLabel;
private JCheckBox[] hobbiesCheckboxes;
private JTextField q1TextField;
private JRadioButton q2Option1RadioButton;
private JRadioButton q2Option2RadioButton;
private JComboBox<String> q3ComboBox;
private JCheckBox q4Option1CheckBox;
private JCheckBox q4Option2CheckBox;
private JCheckBox q4Option3CheckBox;
private JButton submitButton;
private JButton q5Option2Button;
private JButton q5Option4Button;
private JButton q5Option3Button;
private String userName;
private int score = 0;
private String[] hobbies = {"Reading", "Sports", "Music", "Art",
"Travel"};
private String[] q3Options = {"1", "2", "3", "None"};
private JPanel totalScorePanel; // Declare class member for
totalScorePanel

public TestPage() {
frame = new JFrame("Math Test Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2, 10, 10));
frame.setPreferredSize(new Dimension(800, 800)); // Increased
the window size

// Create components
nameField = new JTextField();
phoneField = new JTextField();
aboutYouTextArea = new JTextArea(10, 20);
JScrollPane aboutYouScrollPane = new
JScrollPane(aboutYouTextArea);
ageSlider = new JSlider(18, 30);
ageLabel = new JLabel("Age: " + ageSlider.getValue());
hobbiesCheckboxes = new JCheckBox[hobbies.length];

for (int i = 0; i < hobbies.length; i++) {


hobbiesCheckboxes[i] = new JCheckBox(hobbies[i]);
}

q1TextField = new JTextField();


q2Option1RadioButton = new JRadioButton("4 * sides");
q2Option2RadioButton = new JRadioButton("side * side");
ButtonGroup q2ButtonGroup = new ButtonGroup();
q2ButtonGroup.add(q2Option1RadioButton);
q2ButtonGroup.add(q2Option2RadioButton);
q3ComboBox = new JComboBox<>(q3Options);
q4Option1CheckBox = new JCheckBox("Convex Polygon");
q4Option2CheckBox = new JCheckBox("Cyclic");
q4Option3CheckBox = new JCheckBox("Congruent");
submitButton = new JButton("Submit");

// Set submit button properties


submitButton.setForeground(Color.GREEN);
submitButton.setContentAreaFilled(true);
submitButton.setPreferredSize(new Dimension(50, 40));

// Add components to the frame


frame.add(new JLabel("Name:"));
frame.add(nameField);
frame.add(new JLabel("Phone No.:"));
frame.add(phoneField);
frame.add(new JLabel("About Yourself:"));
frame.add(aboutYouScrollPane);
frame.add(ageLabel);
frame.add(ageSlider);

// Add the label for hobbies


JLabel hobbiesLabel = new JLabel("Hobbies:");
hobbiesLabel.setVerticalAlignment(JLabel.TOP); // Align the
label to the top
frame.add(hobbiesLabel);

// Add the checkboxes for hobbies


JPanel hobbiesPanel = new JPanel();
hobbiesPanel.setLayout(new GridLayout(hobbies.length, 1));

for (JCheckBox checkbox : hobbiesCheckboxes) {


hobbiesPanel.add(checkbox);
}
frame.add(new JScrollPane(hobbiesPanel));

// Add Question 1
frame.add(new JLabel("Q1. What is the value of Pi?"));
frame.add(q1TextField);

// Add Question 2
frame.add(new JLabel("Q2. The perimeter of a cube is:"));
frame.add(q2Option1RadioButton);
frame.add(new JLabel(""));
frame.add(q2Option2RadioButton);
// Add Question 3
frame.add(new JLabel("Q3. How many lines can be drawn through
two points?"));
frame.add(q3ComboBox);

// Add Question 4
frame.add(new JLabel("Q4. A triangle with two sides equal is
known as:"));
frame.add(q4Option1CheckBox);
frame.add(new JLabel(""));
frame.add(q4Option2CheckBox);
frame.add(new JLabel(""));
frame.add(q4Option3CheckBox);

// Add Question 5
frame.add(new JLabel("Q5. How many digits are in 1000?"));
JPanel q5OptionsPanel = new JPanel();
q5OptionsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
q5Option2Button = new JButton("2");
q5Option4Button = new JButton("4");
q5Option3Button = new JButton("3");
q5OptionsPanel.add(q5Option2Button);
q5OptionsPanel.add(q5Option4Button);
q5OptionsPanel.add(q5Option3Button);
frame.add(q5OptionsPanel);

// Add the Submit button


frame.add(new JLabel(""));
frame.add(submitButton);

// Add action listener to update age label


ageSlider.addChangeListener(e -> {
ageLabel.setText("Age: " + ageSlider.getValue());
});

// Add action listener to submit button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (validateInput()) {
evaluateTest();
displayResults();
}
}
});

// Set up the frame


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

private boolean validateInput() {


// Validation for name field (only alphabets, spaces, and dot
allowed)
String name = nameField.getText().trim();

if (!Pattern.matches("[a-zA-Z .]+", name)) {


JOptionPane.showMessageDialog(frame, "Invalid name. Only
alphabets, spaces, and dot allowed.");
return false;
}

// Validation for phone number field (only numbers not


exceeding 10 digits)
String phone = phoneField.getText().trim();

if (!Pattern.matches("\\d{1,10}", phone)) {
JOptionPane.showMessageDialog(frame, "Invalid phone number.
Only numbers not exceeding 10 digits allowed.");
return false;
}

return true; // Input is valid


}

private void evaluateTest() {


// Define the correct answers
String correctPiValue = "3.14";
String correctCubePerimeter = "4 * sides";
String correctLines = "1";
boolean correctConvexPolygon = true;
boolean correctCyclic = false;
boolean correctCongruent = false;

// Get user inputs


userName = nameField.getText();
String userPiValue = q1TextField.getText().trim();
String userCubePerimeter = q2Option1RadioButton.isSelected() ?
"4 * sides" : "side * side";
String userLines = (String) q3ComboBox.getSelectedItem();
boolean userConvexPolygon = q4Option1CheckBox.isSelected();
boolean userCyclic = q4Option2CheckBox.isSelected();
boolean

userCongruent = q4Option3CheckBox.isSelected();
// Calculate the score
score = 0;

if (userPiValue.equals(correctPiValue)) {
score++;
}

if (userCubePerimeter.equals(correctCubePerimeter)) {
score++;
}

if (userLines.equals(correctLines)) {
score++;
}

if (userConvexPolygon == correctConvexPolygon && userCyclic ==


correctCyclic && userCongruent == correctCongruent) {
score++;
}
}

private void displayResults() {


// Create a table to display results
String[] columnNames = {"Question No.", "Your Answer", "Correct
Answer", "Score"};
Object[][] data = {
{"1", q1TextField.getText().trim(), "3.14",
q1TextField.getText().trim().equals("3.14") ? "1" : "0"},
{"2", q2Option1RadioButton.isSelected() ? "4 * sides" :
"side * side", "4 * sides", q2Option1RadioButton.isSelected() ? "4 *
sides".equals("4 * sides") ? "1" : "0" : "side * side".equals("4 *
sides") ? "1" : "0"},
{"3", (String) q3ComboBox.getSelectedItem(), "1",
((String) q3ComboBox.getSelectedItem()).equals("1") ? "1" : "0"},
{"4", getSelectedCheckBoxes(), "Convex Polygon, Cyclic,
Congruent", getSelectedCheckBoxes().equals("Convex Polygon, Cyclic,
Congruent") ? "1" : "0"},
{"5", getSelectedQuestion5Option(), "4",
getSelectedQuestion5Option().equals("4") ? "1" : "0"},
};

JTable table = new JTable(data, columnNames);


table.setPreferredScrollableViewportSize(new Dimension(600,
300)); // Increased table size
table.setFillsViewportHeight(true);

JScrollPane scrollPane = new JScrollPane(table);


// Calculate total score
int totalScore = 0;
for (int i = 0; i < data.length; i++) {
totalScore += Integer.parseInt((String) data[i][3]);
}

// Display the results in a message box


String message = "Test Results for " + userName + "\n\n";
message += String.format("%-15s%-20s%-20s%-10s%n", "Question
No.", "Your Answer", "Correct Answer", "Score");
for (int i = 0; i < data.length; i++) {
message += String.format("%-15s%-20s%-20s%-10s%n",
data[i]);
}
message += "\nTotal Score: " + totalScore + "/5";

// Display total score message


JOptionPane.showMessageDialog(frame, message, "Test Results",
JOptionPane.INFORMATION_MESSAGE);
}

private String getSelectedCheckBoxes() {


StringBuilder selected = new StringBuilder();
if (q4Option1CheckBox.isSelected()) {
selected.append("Convex Polygon, ");
}
if (q4Option2CheckBox.isSelected()) {
selected.append("Cyclic, ");
}
if (q4Option3CheckBox.isSelected()) {
selected.append("Congruent, ");
}
if (selected.length() > 0) {
selected.setLength(selected.length() - 2); // Remove the
trailing comma and space
}
return selected.toString();
}

private String getSelectedQuestion5Option() {


if (q5Option2Button.getModel().isPressed()) {
return q5Option2Button.getText();
} else if (q5Option4Button.getModel().isPressed()) {
return q5Option4Button.getText();
} else if (q5Option3Button.getModel().isPressed()) {
return q5Option3Button.getText();
} else {
return "";
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new TestPage());
}
}

You might also like