0% found this document useful (0 votes)
19 views16 pages

E23CSEU1663 JavaLab7

College B.TECH CSE Tutorial Solution

Uploaded by

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

E23CSEU1663 JavaLab7

College B.TECH CSE Tutorial Solution

Uploaded by

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

Name: Dhiyan Borgohain

Roll No: E23CSEU1663


Batch: 56

Note: Sir, the roll number is mentioned in each snapshot in


the package name of the code.

1. Simple Calculator GUI:


package E23CSEU1663;

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

public class SimpleCalculatorGUI extends JFrame {


private JTextField displayField;
private StringBuilder currentInput;

public SimpleCalculatorGUI() {
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
setLocationRelativeTo(null);

JPanel mainPanel = new JPanel(new BorderLayout());


mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

displayField = new JTextField();


displayField.setEditable(false);
displayField.setHorizontalAlignment(JTextField.RIGHT);
mainPanel.add(displayField, BorderLayout.NORTH);

JPanel buttonPanel = new JPanel(new GridLayout(4, 4, 5, 5));


mainPanel.add(buttonPanel, BorderLayout.CENTER);

currentInput = new StringBuilder();

String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
processInput(label);
}
});
buttonPanel.add(button);
}

add(mainPanel);
setVisible(true);
}

private void processInput(String input) {


if (input.equals("=")) {
try {
double result = evaluateExpression(currentInput.toString());
displayField.setText(String.valueOf(result));
currentInput.setLength(0);
currentInput.append(result);
} catch (ArithmeticException | NumberFormatException ex) {
displayField.setText("Error");
currentInput.setLength(0);
}
} else {
currentInput.append(input);
displayField.setText(currentInput.toString());
}
}

private double evaluateExpression(String expression) {


return new Object() {
int pos = -1, ch;

void nextChar() {
ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
}

boolean eat(int charToEat) {


while (Character.isWhitespace(ch)) nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}

double parse() {
nextChar();
double x = parseExpression();
if (pos < expression.length()) throw new RuntimeException("Unexpected: " + (char) ch);
return x;
}

double parseExpression() {
double x = parseTerm();
for (; ; ) {
if (eat('+')) x += parseTerm();
else if (eat('-')) x -= parseTerm();
else return x;
}
}

double parseTerm() {
double x = parseFactor();
for (; ; ) {
if (eat('*')) x *= parseFactor();
else if (eat('/')) x /= parseFactor();
else return x;
}
}

double parseFactor() {
if (eat('+')) return parseFactor();
if (eat('-')) return -parseFactor();

double x;
int startPos = this.pos;
if (eat('(')) {
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') {
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(expression.substring(startPos, this.pos));
} else {
throw new RuntimeException("Unexpected: " + (char) ch);
}

if (eat('^')) x = Math.pow(x, parseFactor());

return x;
}
}.parse();
}

public static void main(String[] args) {


SwingUtilities.invokeLater(SimpleCalculatorGUI::new);
}
}
2. Address Book GUI:
package E23CSEU1663;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AddressBookGUI extends JFrame {


private JTextField nameField, phoneField, emailField;
private DefaultListModel<String> contactsModel;
private JList<String> contactsList;

public AddressBookGUI() {
setTitle("Address Book");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);

JPanel mainPanel = new JPanel(new BorderLayout());


mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

JPanel formPanel = new JPanel(new GridLayout(3, 2, 5, 5));


formPanel.setBorder(BorderFactory.createTitledBorder("Add New Contact"));

JLabel nameLabel = new JLabel("Name:");


nameField = new JTextField();
JLabel phoneLabel = new JLabel("Phone:");
phoneField = new JTextField();
JLabel emailLabel = new JLabel("Email:");
emailField = new JTextField();

formPanel.add(nameLabel);
formPanel.add(nameField);
formPanel.add(phoneLabel);
formPanel.add(phoneField);
formPanel.add(emailLabel);
formPanel.add(emailField);

JButton addButton = new JButton("Add Contact");


addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addContact();
}
});
formPanel.add(addButton);

mainPanel.add(formPanel, BorderLayout.NORTH);

contactsModel = new DefaultListModel<>();


contactsList = new JList<>(contactsModel);
JScrollPane scrollPane = new JScrollPane(contactsList);
scrollPane.setBorder(BorderFactory.createTitledBorder("Contacts"));

mainPanel.add(scrollPane, BorderLayout.CENTER);

JButton deleteButton = new JButton("Delete Selected");


deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteContact();
}
});
mainPanel.add(deleteButton, BorderLayout.SOUTH);

add(mainPanel);
setVisible(true);
}

private void addContact() {


String name = nameField.getText().trim();
String phone = phoneField.getText().trim();
String email = emailField.getText().trim();

if (name.isEmpty() || phone.isEmpty() || email.isEmpty()) {


JOptionPane.showMessageDialog(this, "Please fill in all fields.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

if (!isValidPhoneNumber(phone)) {
JOptionPane.showMessageDialog(this, "Invalid phone number format.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

if (!isValidEmail(email)) {
JOptionPane.showMessageDialog(this, "Invalid email format.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

String contact = name + " - " + phone + " - " + email;


contactsModel.addElement(contact);

// Clear fields after adding contact


nameField.setText("");
phoneField.setText("");
emailField.setText("");
}

private void deleteContact() {


int selectedIndex = contactsList.getSelectedIndex();
if (selectedIndex != -1) {
contactsModel.remove(selectedIndex);
} else {
JOptionPane.showMessageDialog(this, "Please select a contact to delete.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}

private boolean isValidPhoneNumber(String phone) {


// Simple phone number validation (10 digits)
return phone.matches("\\d{10}");
}

private boolean isValidEmail(String email) {


// Simple email validation
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-
Z]{2,7}$";
Pattern pattern = Pattern.compile(emailRegex);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}

public static void main(String[] args) {


SwingUtilities.invokeLater(AddressBookGUI::new);
}
}
3. Tic-Tac-Toe Game GUI:
package E23CSEU1663;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TicTacToeGUI extends JFrame {


private JButton[][] buttons;
private char currentPlayer;
private JLabel statusLabel;

public TicTacToeGUI() {
setTitle("Tic-Tac-Toe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);

JPanel mainPanel = new JPanel(new BorderLayout());

JPanel boardPanel = new JPanel(new GridLayout(3, 3));


buttons = new JButton[3][3];
initializeBoard(boardPanel);

mainPanel.add(boardPanel, BorderLayout.CENTER);

statusLabel = new JLabel("Player X's turn");


statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
mainPanel.add(statusLabel, BorderLayout.SOUTH);

add(mainPanel);
setVisible(true);
}
private void initializeBoard(JPanel boardPanel) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
JButton button = new JButton();
button.setPreferredSize(new Dimension(100, 100));
button.setFont(new Font("Arial", Font.PLAIN, 40));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (button.getText().isEmpty()) {
button.setText(String.valueOf(currentPlayer));
if (checkWin()) {
statusLabel.setText("Player " + currentPlayer + " wins!");
disableButtons();
} else if (isBoardFull()) {
statusLabel.setText("It's a draw!");
} else {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
statusLabel.setText("Player " + currentPlayer + "'s turn");
}
}
}
});
buttons[i][j] = button;
boardPanel.add(button);
}
}
currentPlayer = 'X';
}

private boolean checkWin() {


// Check rows
for (int i = 0; i < 3; i++) {
if (buttons[i][0].getText().equals(String.valueOf(currentPlayer)) &&
buttons[i][1].getText().equals(String.valueOf(currentPlayer)) &&
buttons[i][2].getText().equals(String.valueOf(currentPlayer))) {
return true;
}
}
// Check columns
for (int j = 0; j < 3; j++) {
if (buttons[0][j].getText().equals(String.valueOf(currentPlayer)) &&
buttons[1][j].getText().equals(String.valueOf(currentPlayer)) &&
buttons[2][j].getText().equals(String.valueOf(currentPlayer))) {
return true;
}
}
// Check diagonals
if (buttons[0][0].getText().equals(String.valueOf(currentPlayer)) &&
buttons[1][1].getText().equals(String.valueOf(currentPlayer)) &&
buttons[2][2].getText().equals(String.valueOf(currentPlayer))) {
return true;
}
if (buttons[0][2].getText().equals(String.valueOf(currentPlayer)) &&
buttons[1][1].getText().equals(String.valueOf(currentPlayer)) &&
buttons[2][0].getText().equals(String.valueOf(currentPlayer))) {
return true;
}
return false;
}

private boolean isBoardFull() {


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (buttons[i][j].getText().isEmpty()) {
return false;
}
}
}
return true;
}

private void disableButtons() {


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setEnabled(false);
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(TicTacToeGUI::new);
}
}
4. To-Do List GUI:
package E23CSEU1663;

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

public class TodoListGUI extends JFrame {


private DefaultListModel<Task> todoListModel;
private JList<Task> todoList;
private JTextField taskField;

public TodoListGUI() {
setTitle("To-Do List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
setLocationRelativeTo(null);

JPanel mainPanel = new JPanel(new BorderLayout());


mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

JPanel inputPanel = new JPanel(new BorderLayout());

taskField = new JTextField();


taskField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addTask();
}
});
inputPanel.add(taskField, BorderLayout.CENTER);
JButton addButton = new JButton("Add Task");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addTask();
}
});
inputPanel.add(addButton, BorderLayout.EAST);

mainPanel.add(inputPanel, BorderLayout.NORTH);

todoListModel = new DefaultListModel<>();


todoList = new JList<>(todoListModel);
todoList.setCellRenderer(new TaskCellRenderer());
todoList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
todoList.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
int index = todoList.locationToIndex(evt.getPoint());
if (index != -1) {
Task task = todoListModel.getElementAt(index);
task.toggleCompleted();
todoList.repaint();
}
}
});

JScrollPane scrollPane = new JScrollPane(todoList);


mainPanel.add(scrollPane, BorderLayout.CENTER);

JButton removeButton = new JButton("Remove Task");


removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeTask();
}
});
mainPanel.add(removeButton, BorderLayout.SOUTH);

add(mainPanel);
setVisible(true);
}

private void addTask() {


String taskDescription = taskField.getText().trim();
if (!taskDescription.isEmpty()) {
Task task = new Task(taskDescription);
todoListModel.addElement(task);
taskField.setText("");
} else {
JOptionPane.showMessageDialog(this, "Task description cannot be empty!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private void removeTask() {
int selectedIndex = todoList.getSelectedIndex();
if (selectedIndex != -1) {
todoListModel.remove(selectedIndex);
} else {
JOptionPane.showMessageDialog(this, "Please select a task to remove.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(TodoListGUI::new);
}

private class Task {


private String description;
private boolean completed;

public Task(String description) {


this.description = description;
}

public String getDescription() {


return description;
}

public boolean isCompleted() {


return completed;
}

public void toggleCompleted() {


completed = !completed;
}

@Override
public String toString() {
return description + (completed ? " [✓]" : "");
}
}

private class TaskCellRenderer extends JCheckBox implements ListCellRenderer<Task> {


public TaskCellRenderer() {
setOpaque(true);
}

@Override
public Component getListCellRendererComponent(JList<? extends Task> list, Task task, int index,
boolean isSelected, boolean cellHasFocus) {
setSelected(task.isCompleted());
setText(task.getDescription());
setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
return this;
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy