Assignment 5: GUI Designing, Event Handling
Set A a) Write a java program that works as a simple calculator. Use a grid
layout to arrange buttons for the digits and for the +, -, *, % operations.
Add a text field to display the result.
Code :
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField displayField;
private String operator = "";
private double operand1 = 0;
private boolean isOperatorClicked = false;
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
displayField = new JTextField();
[Link](false);
[Link](new Font("Arial", [Link], 24));
[Link]([Link]);
add(displayField, [Link]);
JPanel buttonPanel = new JPanel();
[Link](new GridLayout(4, 4, 5, 5));
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
[Link](new Font("Arial", [Link], 20));
[Link](this);
[Link](button);
add(buttonPanel, [Link]);
@Override
public void actionPerformed(ActionEvent e) {
String command = [Link]();
char firstChar = [Link](0);
if ([Link](firstChar) || [Link](".")) {
if (isOperatorClicked || [Link]().equals("0")) {
[Link](command);
isOperatorClicked = false;
} else {
[Link]([Link]() + command);
} else {
if ([Link]("=")) {
if (![Link]()) {
double operand2 =
[Link]([Link]());
double result = 0;
switch (operator) {
case "+": result = operand1 + operand2; break;
case "-": result = operand1 - operand2; break;
case "*": result = operand1 * operand2; break;
case "/":
if (operand2 != 0) {
result = operand1 / operand2;
} else {
[Link]("Error");
return;
break;
[Link]([Link](result));
operator = "";
operand1 = result;
} else {
operator = command;
operand1 = [Link]([Link]());
isOperatorClicked = true;
public static void main(String[] args) {
[Link](() -> {
new SimpleCalculator().setVisible(true);
});
OUTPUT :
b) Design a screen to handle the Mouse Events such as MOUSE_MOVED
and MOUSE_CLICK and display the position of the Mouse_Click in a
TextField.
Code :
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class MouseEventHandler extends JFrame {
private JTextField positionField;
private JLabel instructionLabel;
public MouseEventHandler() {
setTitle("Mouse Event Handler");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
instructionLabel = new JLabel("Click anywhere in the window.");
positionField = new JTextField(20);
[Link](false);
add(instructionLabel);
add(positionField);
[Link](new MyMouseListener());
}
private class MyMouseListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at: (" + [Link]() + ", " +
[Link]() + ")");
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
public static void main(String[] args) {
[Link](() -> {
new MouseEventHandler().setVisible(true);
});
OUTPUT :
Set B
a) Create the following GUI screen using appropriate layout managers.
Accept the name, class , hobbies of the user and apply the changes
and display the selected options in a text box.
Code :
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class UserDetailsForm extends JFrame implements ActionListener {
private JTextField nameField, displayField;
private JRadioButton fyRadio, syRadio, tyRadio;
private JCheckBox musicCheck, sportsCheck, travelCheck;
private JComboBox<String> fontComboBox;
private JComboBox<Integer> sizeComboBox;
private JCheckBox boldCheck, italicCheck;
public UserDetailsForm() {
setTitle("User Details");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(6, 1));
JPanel namePanel = new JPanel(new FlowLayout([Link]));
[Link](new JLabel("Your Name:"));
nameField = new JTextField(20);
[Link](this);
[Link](nameField);
add(namePanel);
JPanel selectionsPanel = new JPanel(new GridLayout(1, 2));
JPanel classPanel = new JPanel();
[Link]([Link]("Your Class"));
fyRadio = new JRadioButton("FY");
syRadio = new JRadioButton("SY", true);
tyRadio = new JRadioButton("TY");
ButtonGroup classGroup = new ButtonGroup();
[Link](fyRadio); [Link](syRadio);
[Link](tyRadio);
[Link](fyRadio); [Link](syRadio);
[Link](tyRadio);
[Link](classPanel);
[Link](this); [Link](this);
[Link](this);
JPanel hobbiesPanel = new JPanel();
[Link]([Link]("Your
Hobbies"));
musicCheck = new JCheckBox("Music");
sportsCheck = new JCheckBox("Sports");
travelCheck = new JCheckBox("Travelling");
[Link](musicCheck); [Link](sportsCheck);
[Link](travelCheck);
[Link](hobbiesPanel);
add(selectionsPanel);
[Link](this);
[Link](this); [Link](this);
JPanel stylePanel = new JPanel(new GridLayout(1, 2));
JPanel fontPanel = new JPanel();
[Link]([Link]("Font"));
fontComboBox = new JComboBox<>(new String[]{"Arial", "Times
New Roman", "Courier New"});
sizeComboBox = new JComboBox<>(new Integer[]{8, 12, 16, 20});
[Link](new JLabel("Font:")); [Link](fontComboBox);
[Link](new JLabel("Size:")); [Link](sizeComboBox);
[Link](fontPanel);
[Link](this);
[Link](this);
JPanel textStylePanel = new JPanel();
[Link]([Link]("Style"));
boldCheck = new JCheckBox("Bold");
italicCheck = new JCheckBox("Italic");
[Link](boldCheck); [Link](italicCheck);
[Link](textStylePanel);
add(stylePanel);
[Link](this);
[Link](this);
JPanel displayPanel = new JPanel(new FlowLayout([Link]));
displayField = new JTextField(40);
[Link](false);
[Link](new JLabel("Output:"));
[Link](displayField);
add(displayPanel);
updateDisplay();
@Override
public void actionPerformed(ActionEvent e) {
updateDisplay();
private void updateDisplay() {
String name = [Link]();
String userClass = "";
if ([Link]()) userClass = "FY";
else if ([Link]()) userClass = "SY";
else if ([Link]()) userClass = "TY";
StringBuilder hobbies = new StringBuilder();
if ([Link]()) [Link]("Music ");
if ([Link]()) [Link]("Sports ");
if ([Link]()) [Link]("Travelling");
[Link]("Name: " + name + " | Class: " + userClass + " |
Hobbies: " + [Link]());
String fontName = (String) [Link]();
int fontSize = (Integer) [Link]();
int style = [Link];
if([Link]()) style |= [Link];
if([Link]()) style |= [Link];
[Link](new Font(fontName, style, fontSize));
public static void main(String[] args) {
[Link](() -> new
UserDetailsForm().setVisible(true));
OUTPUT :
b) Write a Java program to design a screen using Awt that will take a
user name and password. If the user name and password are not
same, raise an Exception with appropriate message. User can have
3 login chances only. Use clear button to clear the TextFields.
Code :
import [Link].*;
import [Link].*;
class LoginFailedException extends Exception {
public LoginFailedException(String message) {
super(message);
public class AwtLoginScreen extends Frame implements ActionListener
{
private TextField userField, passField;
private Button loginButton, clearButton;
private Label statusLabel;
private int loginAttempts = 0;
private static final int MAX_ATTEMPTS = 3;
public AwtLoginScreen() {
setTitle("AWT Login");
setSize(400, 200);
setLayout(new GridLayout(4, 2, 10, 10));
setLocationRelativeTo(null);
add(new Label("Username:"));
userField = new TextField();
add(userField);
add(new Label("Password:"));
passField = new TextField();
[Link]('*');
add(passField);
loginButton = new Button("Login");
[Link](this);
add(loginButton);
clearButton = new Button("Clear");
[Link](this);
add(clearButton);
statusLabel = new Label("You have " + MAX_ATTEMPTS + "
attempts remaining.", [Link]);
add(statusLabel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
});
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]() == loginButton) {
handleLogin();
} else if ([Link]() == clearButton) {
[Link]("");
[Link]("");
private void handleLogin() {
String username = [Link]();
String password = [Link]();
try {
if () {
loginAttempts++;
int attemptsLeft = MAX_ATTEMPTS - loginAttempts;
if (attemptsLeft > 0) {
[Link]("Attempts remaining: " +
attemptsLeft);
throw new LoginFailedException("Username and password
do not match.");
} else {
[Link]("Login failed. No attempts left.");
[Link](false);
} else {
[Link]("Login Successful!");
[Link](false);
[Link](false);
}
} catch (LoginFailedException ex) {
[Link]([Link]());
public static void main(String[] args) {
new AwtLoginScreen().setVisible(true);
OUTPUT :
Set C
a) Write a java program to create the following GUI for user
registration form
If above conditions are met, display “Registration Successful”
otherwise “Registration Failed” after the user clicks the Submit button.
Code :
import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link];
public class CoWinRegistrationForm extends JFrame implements
ActionListener {
private JTextField adharField, mobileField;
private JComboBox<Integer> yearComboBox;
private JComboBox<String> hospitalComboBox;
private JRadioButton age18Plus, age45Plus;
private JRadioButton covishield, covaxin, sputnik;
private JRadioButton morning, afternoon, evening;
private JButton submitButton;
public CoWinRegistrationForm() {
setTitle("Co-WIN Registration");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(8, 2, 5, 5));
setLocationRelativeTo(null);
add(new JLabel("AadharCard No.:"));
adharField = new JTextField();
add(adharField);
add(new JLabel("Birth Year:"));
yearComboBox = new JComboBox<>();
int currentYear = [Link]().get([Link]);
for (int i = currentYear - 100; i <= currentYear; i++) {
[Link](i);
add(yearComboBox);
add(new JLabel("Mobile No.:"));
mobileField = new JTextField();
add(mobileField);
add(new JLabel("Age Group:"));
JPanel agePanel = new JPanel();
age18Plus = new JRadioButton("18 & above", true);
age45Plus = new JRadioButton("45 & above");
ButtonGroup ageGroup = new ButtonGroup();
[Link](age18Plus); [Link](age45Plus);
[Link](age18Plus); [Link](age45Plus);
add(agePanel);
add(new JLabel("Select Hospital:"));
hospitalComboBox = new JComboBox<>(new String[]{"City
Hospital", "General Hospital", "Sunrise Hospital"});
add(hospitalComboBox);
add(new JLabel("Vaccines:"));
JPanel vaccinePanel = new JPanel();
covishield = new JRadioButton("Covishield", true);
covaxin = new JRadioButton("Covaxin");
sputnik = new JRadioButton("Sputnik V");
ButtonGroup vaccineGroup = new ButtonGroup();
[Link](covishield); [Link](covaxin);
[Link](sputnik);
[Link](covishield); [Link](covaxin);
[Link](sputnik);
add(vaccinePanel);
add(new JLabel("Time Slot:"));
JPanel timePanel = new JPanel();
morning = new JRadioButton("Morning", true);
afternoon = new JRadioButton("Afternoon");
evening = new JRadioButton("Evening");
ButtonGroup timeGroup = new ButtonGroup();
[Link](morning); [Link](afternoon);
[Link](evening);
[Link](morning); [Link](afternoon);
[Link](evening);
add(timePanel);
submitButton = new JButton("Submit");
[Link](this);
add(new JLabel());
add(submitButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]() == submitButton) {
if ([Link]().trim().isEmpty() ||
[Link]().trim().isEmpty()) {
[Link](this, "Registration Failed:
Please fill all fields.", "Error", JOptionPane.ERROR_MESSAGE);
} else {
[Link](this, "Registration
Successful!", "Success", JOptionPane.INFORMATION_MESSAGE);
public static void main(String[] args) {
[Link](() -> new
CoWinRegistrationForm().setVisible(true));
OUTPUT :
b) Write a program to display the following menus and sub-menus
Code :
import [Link].*;
public class MenuExample extends JFrame {
public MenuExample() {
setTitle("MenuBar, Menu and Menu Items");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenu saveAsMenu = new JMenu("Save As");
JMenuItem pptItem = new JMenuItem("ppt");
JMenuItem docItem = new JMenuItem("doc");
JMenuItem pdfItem = new JMenuItem("pdf");
[Link](pptItem);
[Link](docItem);
[Link](pdfItem);
[Link](newItem);
[Link](openItem);
[Link](saveItem);
[Link]();
[Link](saveAsMenu);
[Link](fileMenu);
setJMenuBar(menuBar);
public static void main(String[] args) {
[Link](() -> new MenuExample().setVisible(true));
OUTPUT :