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

Imports

The document outlines a Java-based Contact Management System that allows users to add, view, update, delete, and search for contacts stored in a MySQL database. It includes classes for managing contacts and a graphical user interface using Swing components. The system ensures phone number validation and handles database connections and operations efficiently.

Uploaded by

abduaragaw1996
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)
7 views14 pages

Imports

The document outlines a Java-based Contact Management System that allows users to add, view, update, delete, and search for contacts stored in a MySQL database. It includes classes for managing contacts and a graphical user interface using Swing components. The system ensures phone number validation and handles database connections and operations efficiently.

Uploaded by

abduaragaw1996
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

package contactmanagementsystem;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.*;

import java.util.ArrayList;

class Contact {

private int id;

private String name;

private String phoneNumber;

public Contact(int id, String name, String phoneNumber) {

this.id = id;

this.name = name;

this.phoneNumber = phoneNumber;

public int getId() { return id; }

public void setId(int id) { this.id = id; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public String getPhoneNumber() { return phoneNumber; }


public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }

@Override

public String toString() {

return "Name: " + name + "\nPhone: " + phoneNumber;

class ContactManager {

private static final String URL = "jdbc:mysql://localhost:3306/contact_db";

private static final String USER = "root";

private static final String PASSWORD = "password";

private Connection connection;

public ContactManager() {

try {

connection = DriverManager.getConnection(URL, USER, PASSWORD);

createTableIfNotExists();

} catch (SQLException e) {

showError("Database connection failed: " + e.getMessage());

private void createTableIfNotExists() throws SQLException {

String sql = "CREATE TABLE IF NOT EXISTS contacts (" +


"id INT PRIMARY KEY AUTO_INCREMENT," +

"name VARCHAR(100) NOT NULL," +

"phone_number VARCHAR(10) NOT NULL UNIQUE)";

try (Statement stmt = connection.createStatement()) {

stmt.execute(sql);

public void addContact(Contact contact) {

if (!isValidPhoneNumber(contact.getPhoneNumber())) {

showError("Invalid phone number format (must be 10 digits)");

return;

String sql = "INSERT INTO contacts (name, phone_number) VALUES (?, ?)";

try (PreparedStatement pstmt = connection.prepareStatement(sql,


Statement.RETURN_GENERATED_KEYS)) {

pstmt.setString(1, contact.getName());

pstmt.setString(2, contact.getPhoneNumber());

pstmt.executeUpdate();

try (ResultSet rs = pstmt.getGeneratedKeys()) {

if (rs.next()) {

contact.setId(rs.getInt(1));

}
JOptionPane.showMessageDialog(null, "Contact added successfully!");

} catch (SQLException e) {

showError("Database error: " + e.getMessage());

public ArrayList<Contact> getAllContacts() {

ArrayList<Contact> contacts = new ArrayList<>();

String sql = "SELECT * FROM contacts ORDER BY name";

try (Statement stmt = connection.createStatement();

ResultSet rs = stmt.executeQuery(sql)) {

while (rs.next()) {

contacts.add(new Contact(

rs.getInt("id"),

rs.getString("name"),

rs.getString("phone_number")

));

} catch (SQLException e) {

showError("Error loading contacts: " + e.getMessage());

return contacts;

}
public void updateContact(Contact contact) {

if (!isValidPhoneNumber(contact.getPhoneNumber())) {

showError("Invalid phone number format (must be 10 digits)");

return;

String sql = "UPDATE contacts SET name = ?, phone_number = ? WHERE id = ?";

try (PreparedStatement pstmt = connection.prepareStatement(sql)) {

pstmt.setString(1, contact.getName());

pstmt.setString(2, contact.getPhoneNumber());

pstmt.setInt(3, contact.getId());

pstmt.executeUpdate();

JOptionPane.showMessageDialog(null, "Contact updated successfully!");

} catch (SQLException e) {

showError("Database error: " + e.getMessage());

public void deleteContact(int id) {

String sql = "DELETE FROM contacts WHERE id = ?";

try (PreparedStatement pstmt = connection.prepareStatement(sql)) {

pstmt.setInt(1, id);

pstmt.executeUpdate();

JOptionPane.showMessageDialog(null, "Contact deleted successfully!");


} catch (SQLException e) {

showError("Database error: " + e.getMessage());

public ArrayList<Contact> searchContacts(String keyword) {

ArrayList<Contact> results = new ArrayList<>();

String sql = "SELECT * FROM contacts WHERE name LIKE ? OR phone_number LIKE ?";

try (PreparedStatement pstmt = connection.prepareStatement(sql)) {

pstmt.setString(1, "%" + keyword + "%");

pstmt.setString(2, "%" + keyword + "%");

try (ResultSet rs = pstmt.executeQuery()) {

while (rs.next()) {

results.add(new Contact(

rs.getInt("id"),

rs.getString("name"),

rs.getString("phone_number")

));

} catch (SQLException e) {

showError("Search error: " + e.getMessage());

}
return results;

private boolean isValidPhoneNumber(String phoneNumber) {

return phoneNumber.matches("\\d{10}");

private void showError(String message) {

JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);

public Connection getConnection() { return connection; }

public class ContactManagementSystem extends JFrame {

private ContactManager contactManager = new ContactManager();

private JList<String> contactList;

private DefaultListModel<String> listModel;

private ArrayList<Contact> currentContacts = new ArrayList<>();

public ContactManagementSystem() {

setTitle("Contact Management System");

setSize(600, 500);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);
initializeUI();

private void initializeUI() {

listModel = new DefaultListModel<>();

contactList = new JList<>(listModel);

contactList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

contactList.setFont(new Font("Arial", Font.PLAIN, 14));

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

JButton viewButton = new JButton("View Contacts");

JButton updateButton = new JButton("Update Contact");

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

JButton searchButton = new JButton("Search Contacts");

JButton exitButton = new JButton("Exit");

JPanel buttonPanel = new JPanel(new GridLayout(6, 1, 5, 5));

buttonPanel.add(addButton);

buttonPanel.add(viewButton);

buttonPanel.add(updateButton);

buttonPanel.add(deleteButton);

buttonPanel.add(searchButton);

buttonPanel.add(exitButton);
JScrollPane scrollPane = new JScrollPane(contactList);

Container container = getContentPane();

container.setLayout(new BorderLayout(10, 10));

container.add(scrollPane, BorderLayout.CENTER);

container.add(buttonPanel, BorderLayout.EAST);

addButton.addActionListener(e -> addContact());

viewButton.addActionListener(e -> viewContacts());

updateButton.addActionListener(e -> updateContact());

deleteButton.addActionListener(e -> deleteContact());

searchButton.addActionListener(e -> searchContacts());

exitButton.addActionListener(e -> System.exit(0));

private void addContact() {

JPanel panel = new JPanel(new GridLayout(3, 2));

JTextField nameField = new JTextField();

JTextField phoneField = new JTextField();

panel.add(new JLabel("Name:"));

panel.add(nameField);

panel.add(new JLabel("Phone (10 digits):"));

panel.add(phoneField);
int result = JOptionPane.showConfirmDialog(null, panel, "Add New Contact",

JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {

String name = nameField.getText().trim();

String phone = phoneField.getText().trim();

if (!name.isEmpty() && !phone.isEmpty()) {

contactManager.addContact(new Contact(0, name, phone));

viewContacts();

} else {

JOptionPane.showMessageDialog(this, "Please fill in all fields.",

"Error", JOptionPane.ERROR_MESSAGE);

private void viewContacts() {

listModel.clear();

currentContacts = contactManager.getAllContacts();

if (currentContacts.isEmpty()) {

listModel.addElement("No contacts available.");

return;

}
for (Contact contact : currentContacts) {

listModel.addElement(contact.getName() + " - " + contact.getPhoneNumber());

private void updateContact() {

int selectedIndex = contactList.getSelectedIndex();

if (selectedIndex == -1) {

JOptionPane.showMessageDialog(this, "Please select a contact to update.",

"Error", JOptionPane.ERROR_MESSAGE);

return;

Contact contact = currentContacts.get(selectedIndex);

JPanel panel = new JPanel(new GridLayout(3, 2));

JTextField nameField = new JTextField(contact.getName());

JTextField phoneField = new JTextField(contact.getPhoneNumber());

panel.add(new JLabel("Name:"));

panel.add(nameField);

panel.add(new JLabel("Phone:"));

panel.add(phoneField);

int result = JOptionPane.showConfirmDialog(null, panel, "Update Contact",


JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {

contact.setName(nameField.getText().trim());

contact.setPhoneNumber(phoneField.getText().trim());

contactManager.updateContact(contact);

viewContacts();

private void deleteContact() {

int selectedIndex = contactList.getSelectedIndex();

if (selectedIndex == -1) {

JOptionPane.showMessageDialog(this, "Please select a contact to delete.",

"Error", JOptionPane.ERROR_MESSAGE);

return;

int confirm = JOptionPane.showConfirmDialog(this,

"Are you sure you want to delete this contact?",

"Confirm Delete", JOptionPane.YES_NO_OPTION);

if (confirm == JOptionPane.YES_OPTION) {

Contact contact = currentContacts.get(selectedIndex);

contactManager.deleteContact(contact.getId());
viewContacts();

private void searchContacts() {

String keyword = JOptionPane.showInputDialog(this, "Enter search keyword:");

if (keyword == null || keyword.trim().isEmpty()) return;

listModel.clear();

currentContacts = contactManager.searchContacts(keyword.trim());

if (currentContacts.isEmpty()) {

listModel.addElement("No matching contacts found.");

return;

for (Contact contact : currentContacts) {

listModel.addElement(contact.getName() + " - " + contact.getPhoneNumber());

public static void main(String[] args) {

try {

Class.forName("com.mysql.cj.jdbc.Driver");

SwingUtilities.invokeLater(() -> {
ContactManagementSystem cms = new ContactManagementSystem();

cms.setVisible(true);

try {

if (cms.contactManager.getConnection().isClosed()) {

JOptionPane.showMessageDialog(null, "Database connection failed");

System.exit(1);

} catch (SQLException e) {

JOptionPane.showMessageDialog(null, "Database error: " + e.getMessage());

System.exit(1);

});

} catch (ClassNotFoundException e) {

JOptionPane.showMessageDialog(null, "MySQL Driver not found!");

System.exit(1);

You might also like