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

ADV.JAVA micro

The document outlines the development of an Expense Tracker Manager using Advanced Java and MySQL, featuring a GUI with tabs for Income, Expense, and Comparison. It includes functionalities for adding, deleting, and displaying income and expense records, as well as calculating totals and visualizing comparisons through a progress bar. The program utilizes various Swing components and JDBC for secure database interactions, ensuring data integrity and user-friendly experience.

Uploaded by

royalkingkaranja
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)
2 views16 pages

ADV.JAVA micro

The document outlines the development of an Expense Tracker Manager using Advanced Java and MySQL, featuring a GUI with tabs for Income, Expense, and Comparison. It includes functionalities for adding, deleting, and displaying income and expense records, as well as calculating totals and visualizing comparisons through a progress bar. The program utilizes various Swing components and JDBC for secure database interactions, ensuring data integrity and user-friendly experience.

Uploaded by

royalkingkaranja
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

• Aim : Develop an Expense Tracker Manager using Advanced Java and

MySql Database.

About the program / Working of program :-

 User Interface: The program features a graphical user interface (GUI) created using
Swing components, including text fields, buttons, tables, and labels for displaying
income and expense data.

 Tabbed Layout: The GUI is organized into a tabbed pane with three tabs: Income,
Expense, and Comparison. This structure allows users to navigate easily between
different functionalities.

 Database Connection: The program connects to a MySQL database


(ExpenseTrackerDB) to store, retrieve, and manipulate income and expense records. The
connection is established using JDBC (Java Database Connectivity).

 Adding Income: Users can input income details (description, amount, and date) and
click the "Add Income" button to store the data in the database. The income is
categorized as "Income" in the database.

 Adding Expense: Similar to adding income, users can input expense details and click the
"Add Expense" button to save the data. The expense is categorized as "Expense" in the
database.

 Data Validation: The program validates user inputs for amount fields to ensure they are
numeric. If an invalid input is detected, an error message is displayed using a dialog box.

 Displaying Records: The income and expense records are displayed in separate tables
within their respective tabs, allowing users to view all entries at a glance.

 Deleting Records: Users can select a row from the income or expense table and click the
"Delete" button to remove the selected record from the database and the table.

 Clearing Input Fields: The program provides options to clear input fields after adding or
deleting records, enhancing usability and preventing accidental re-entry.

 Resetting All Data: A "Reset All" button allows users to delete all records from the
database, giving them a fresh start if desired.

 Calculating Totals: The program calculates and displays total income, total expenses,
and the balance (income - expenses) at the bottom of the window, updating these values
automatically whenever records are added or deleted.

 Comparison Progress Bar: The program features a progress bar in the Comparison tab,
visually representing the percentage of expenses relative to total income, helping users
understand their financial situation at a glance.

 Database Interaction: The program uses prepared statements to interact with the
database securely, preventing SQL injection attacks and ensuring data integrity.
• About the Swing Components which are used in project : -
1. JFrame:
o Description: Represents the main window of the application. It serves as the
container for all other GUI components and defines the overall layout and
behavior of the application.
o Functionality: It can be customized with titles, dimensions, and default close
operations.

2. JTabbedPane:
o Description: A component that allows for tabbed navigation between multiple
panels or views within the same window.
o Functionality: Users can switch between different sections (like Income, Expense,
Comparison) by clicking on the tabs, making the interface more organized and
user-friendly.

3. JPanel:
o Description: A generic container used to group other components. It can have
different layouts to arrange its child components.
o Functionality: Helps in organizing the user interface into logical sections,
enhancing layout management.

4. JTextField:
o Description: A single-line text input field where users can enter data.
o Functionality: Useful for collecting user inputs like descriptions, amounts, and
dates for income or expenses.

5. JLabel:
o Description: Displays a short string or an image icon. It's generally used for text
annotations.
o Functionality: Provides descriptive text next to input fields or buttons, enhancing
user understanding of the UI.

6. JButton:
o Description: A push-button that triggers an action when clicked.
o Functionality: Commonly used for performing actions like adding, deleting, or
saving entries in the application.

7. JTable:
o Description: Displays data in a tabular format, organizing it into rows and
columns.
o Functionality: Provides a clear view of income and expense records, making it
easier to read and manipulate data.

8. JScrollPane:
o Description: A container that adds scroll bars to another component, allowing for
navigation through large amounts of content.
o Functionality: Used with JTable to ensure that if there are many records, users can
scroll to see all entries.
9. JProgressBar:
o Description: Visually indicates the progress of a task or process.
o Functionality: Used to show a comparison between income and expenses, giving
a visual cue of financial status.

10. GridLayout:
o Description: A layout manager that arranges components in a grid format, defined
by rows and columns.
o Functionality: Useful for organizing input fields and buttons systematically within
the application.

11. BorderLayout:
o Description: A layout manager that organizes components in five regions: north,
south, east, west, and center.
o Functionality: Helps in structuring the main window effectively, allowing for a
flexible arrangement of components.

12. JOptionPane:
o Description: A standard dialog box for displaying messages, warnings, or asking
for user input.
o Functionality: Used for notifications, confirmations, or alerts to the user regarding
actions performed in the application.

13. ActionListener:
o Description: An interface for receiving action events (like button clicks).
o Functionality: Allows defining specific actions that should occur when a user
interacts with components like buttons.

14. DefaultTableModel:
o Description: A data model for JTable that allows adding, removing, and
managing rows and columns of data.
o Functionality: Facilitates easy manipulation of the table's data, supporting
dynamic updates as users add or remove records.

15. GridBagLayout:
o Description: A flexible layout manager that allows for complex arrangements of
components using a grid of cells.
o Functionality: Provides greater control over component positioning, sizes, and
alignment, useful for creating sophisticated UIs.
Program :-

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class ExpenseTrackerGUI extends JFrame {


private static final String URL = "jdbc:mysql://localhost:3306/ExpenseTrackerDB";
private static final String USER = "root"; // Your MySQL username
private static final String PASSWORD = "super"; // Your MySQL password

private JTextField incomeDescriptionField;


private JTextField incomeAmountField;
private JTextField incomeDateField;
private JTextField expenseDescriptionField;
private JTextField expenseAmountField;
private JTextField expenseDateField;
private JTable incomeTable;
private JTable expenseTable;
private DefaultTableModel incomeTableModel;
private DefaultTableModel expenseTableModel;

private JLabel totalIncomeLabel;


private JLabel totalExpenseLabel;
private JLabel balanceLabel;

private JProgressBar incomeExpenseComparisonBar;

public ExpenseTrackerGUI() {
setTitle("Expense Tracker");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
getContentPane().setBackground(new Color(230, 230, 250)); // Light lavender
background

// Create a tabbed pane


JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBackground(new Color(255, 255, 255)); // White background for tabs
tabbedPane.setForeground(new Color(72, 61, 139)); // Dark slate blue text color
// Income panel
JPanel incomePanel = new JPanel();
incomePanel.setLayout(new BorderLayout());
incomePanel.setBackground(new Color(255, 255, 255)); // White background for
income panel

// Income input panel


JPanel incomeInputPanel = new JPanel(new GridLayout(6, 2, 10, 10));
incomeInputPanel.setBackground(new Color(255, 255, 255)); // White background

// Input fields with labels


incomeInputPanel.add(new JLabel("Description:"));
incomeDescriptionField = new JTextField();
incomeInputPanel.add(incomeDescriptionField);

incomeInputPanel.add(new JLabel("Amount:"));
incomeAmountField = new JTextField();
incomeInputPanel.add(incomeAmountField);

incomeInputPanel.add(new JLabel("Date (YYYY-MM-DD):"));


incomeDateField = new JTextField();
incomeInputPanel.add(incomeDateField);

// Buttons with custom background colors


JButton addIncomeButton = new JButton("Add Income");
addIncomeButton.setBackground(new Color(50, 205, 50)); // Lime green
addIncomeButton.setForeground(Color.WHITE);
addIncomeButton.addActionListener(new AddIncomeAction());
incomeInputPanel.add(addIncomeButton);

JButton clearIncomeButton = new JButton("Clear Fields");


clearIncomeButton.setBackground(new Color(255, 69, 0)); // Red-Orange
clearIncomeButton.setForeground(Color.WHITE);
clearIncomeButton.addActionListener(e -> clearIncomeFields());
incomeInputPanel.add(clearIncomeButton);

JButton deleteIncomeButton = new JButton("Delete Income");


deleteIncomeButton.setBackground(new Color(255, 69, 0)); // Red-Orange
deleteIncomeButton.setForeground(Color.WHITE);
deleteIncomeButton.addActionListener(new DeleteIncomeAction());
incomeInputPanel.add(deleteIncomeButton);
incomePanel.add(incomeInputPanel, BorderLayout.NORTH);

// Income table
incomeTableModel = new DefaultTableModel(new String[]{"ID", "Description",
"Amount", "Date"}, 0);
incomeTable = new JTable(incomeTableModel);
incomeTable.setFillsViewportHeight(true);
incomeTable.setBackground(new Color(240, 248, 255)); // Alice blue
incomeTable.setForeground(new Color(0, 0, 128)); // Navy blue
JScrollPane incomeScrollPane = new JScrollPane(incomeTable);
incomePanel.add(incomeScrollPane, BorderLayout.CENTER);

tabbedPane.addTab("Income", incomePanel);

// Expense panel
JPanel expensePanel = new JPanel();
expensePanel.setLayout(new BorderLayout());
expensePanel.setBackground(new Color(255, 255, 255)); // White background for
expense panel

// Expense input panel


JPanel expenseInputPanel = new JPanel(new GridLayout(6, 2, 10, 10));
expenseInputPanel.setBackground(new Color(255, 255, 255)); // White background

expenseInputPanel.add(new JLabel("Description:"));
expenseDescriptionField = new JTextField();
expenseInputPanel.add(expenseDescriptionField);

expenseInputPanel.add(new JLabel("Amount:"));
expenseAmountField = new JTextField();
expenseInputPanel.add(expenseAmountField);

expenseInputPanel.add(new JLabel("Date (YYYY-MM-DD):"));


expenseDateField = new JTextField();
expenseInputPanel.add(expenseDateField);

JButton addExpenseButton = new JButton("Add Expense");


addExpenseButton.setBackground(new Color(50, 205, 50)); // Lime green
addExpenseButton.setForeground(Color.WHITE);
addExpenseButton.addActionListener(new AddExpenseAction());
expenseInputPanel.add(addExpenseButton);
JButton clearExpenseButton = new JButton("Clear Fields");
clearExpenseButton.setBackground(new Color(255, 69, 0)); // Red-Orange
clearExpenseButton.setForeground(Color.WHITE);
clearExpenseButton.addActionListener(e -> clearExpenseFields());
expenseInputPanel.add(clearExpenseButton);

JButton deleteExpenseButton = new JButton("Delete Expense");


deleteExpenseButton.setBackground(new Color(255, 69, 0)); // Red-Orange
deleteExpenseButton.setForeground(Color.WHITE);
deleteExpenseButton.addActionListener(new DeleteExpenseAction());
expenseInputPanel.add(deleteExpenseButton);

expensePanel.add(expenseInputPanel, BorderLayout.NORTH);

// Expense table
expenseTableModel = new DefaultTableModel(new String[]{"ID", "Description",
"Amount", "Date"}, 0);
expenseTable = new JTable(expenseTableModel);
expenseTable.setFillsViewportHeight(true);
expenseTable.setBackground(new Color(240, 248, 255)); // Alice blue
expenseTable.setForeground(new Color(0, 0, 128)); // Navy blue
JScrollPane expenseScrollPane = new JScrollPane(expenseTable);
expensePanel.add(expenseScrollPane, BorderLayout.CENTER);

tabbedPane.addTab("Expense", expensePanel);

// Comparison tab
JPanel comparisonPanel = new JPanel(new BorderLayout());
comparisonPanel.setBackground(new Color(255, 255, 255)); // White background

// Comparison Progress Bar


incomeExpenseComparisonBar = new JProgressBar();
incomeExpenseComparisonBar.setStringPainted(true);
updateComparisonBar(0, 0); // Initialize with zero values

comparisonPanel.add(new JLabel("Income vs Expense Comparison"),


BorderLayout.NORTH);
comparisonPanel.add(incomeExpenseComparisonBar, BorderLayout.CENTER);

tabbedPane.addTab("Comparison", comparisonPanel);

// Total labels
JPanel totalPanel = new JPanel(new GridLayout(4, 1));
totalPanel.setBackground(new Color(255, 255, 255)); // White background

totalIncomeLabel = new JLabel("Total Income: $0.00");


totalIncomeLabel.setForeground(new Color(0, 128, 0)); // Dark green
totalExpenseLabel = new JLabel("Total Expenses: $0.00");
totalExpenseLabel.setForeground(new Color(178, 34, 34)); // Firebrick
balanceLabel = new JLabel("Total Balance: $0.00");
balanceLabel.setForeground(new Color(0, 0, 128)); // Navy blue

// Reset all button


JButton resetButton = new JButton("Reset All");
resetButton.setBackground(new Color(255, 69, 0)); // Red-Orange
resetButton.setForeground(Color.WHITE);
resetButton.addActionListener(new ResetAllAction());
totalPanel.add(resetButton); // Add reset button to the total panel
totalPanel.add(totalIncomeLabel);
totalPanel.add(totalExpenseLabel);
totalPanel.add(balanceLabel);

add(tabbedPane, BorderLayout.CENTER);
add(totalPanel, BorderLayout.SOUTH);

loadRecords(); // Load records on startup

setVisible(true);
}

private class AddIncomeAction implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
String description = incomeDescriptionField.getText();
double amount;
String date = incomeDateField.getText();

// Validate amount input


try {
amount = Double.parseDouble(incomeAmountField.getText());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(ExpenseTrackerGUI.this, "Invalid
amount!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}

String query = "INSERT INTO expenses (description, amount, date, type)


VALUES (?, ?, ?, 'Income')";
try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, description);
pstmt.setDouble(2, amount);
pstmt.setDate(3, Date.valueOf(date));
pstmt.executeUpdate();

} catch (SQLException ex) {


ex.printStackTrace();
JOptionPane.showMessageDialog(ExpenseTrackerGUI.this, "Error adding
income!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}

loadRecords();
clearIncomeFields();
}
}

private class AddExpenseAction implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
String description = expenseDescriptionField.getText();
double amount;
String date = expenseDateField.getText();

// Validate amount input


try {
amount = Double.parseDouble(expenseAmountField.getText());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(ExpenseTrackerGUI.this, "Invalid
amount!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}

String query = "INSERT INTO expenses (description, amount, date, type)


VALUES (?, ?, ?, 'Expense')";
try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, description);
pstmt.setDouble(2, amount);
pstmt.setDate(3, Date.valueOf(date));

pstmt.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(ExpenseTrackerGUI.this, "Error adding
expense!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}

loadRecords();
clearExpenseFields();
}
}

private class DeleteIncomeAction implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = incomeTable.getSelectedRow();
if (selectedRow != -1) {
int id = (Integer) incomeTableModel.getValueAt(selectedRow, 0);
String query = "DELETE FROM expenses WHERE id = ?";
try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);
PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(ExpenseTrackerGUI.this, "Error deleting
income!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}

loadRecords();
}
}
}

private class DeleteExpenseAction implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = expenseTable.getSelectedRow();
if (selectedRow != -1) {
int id = (Integer) expenseTableModel.getValueAt(selectedRow, 0);
String query = "DELETE FROM expenses WHERE id = ?";
try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);

PreparedStatement pstmt = conn.prepareStatement(query)) {


pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(ExpenseTrackerGUI.this, "Error deleting
expense!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}

loadRecords();
}
}
}

private void loadRecords() {


incomeTableModel.setRowCount(0);
expenseTableModel.setRowCount(0);
double totalIncome = 0;
double totalExpense = 0;

String query = "SELECT * FROM expenses";


try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
int id = rs.getInt("id");
String description = rs.getString("description");
double amount = rs.getDouble("amount");
String date = rs.getDate("date").toString();
String type = rs.getString("type");

if ("Income".equals(type)) {
incomeTableModel.addRow(new Object[]{id, description, amount, date});
totalIncome += amount;
} else {
expenseTableModel.addRow(new Object[]{id, description, amount, date});
totalExpense += amount;
}
}
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error loading records!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

totalIncomeLabel.setText("Total Income: ₹" + String.format("%.2f", totalIncome));


totalExpenseLabel.setText("Total Expenses: ₹" + String.format("%.2f",
totalExpense));
double balance = totalIncome - totalExpense;
balanceLabel.setText("Total Balance: ₹" + String.format("%.2f", balance));

updateComparisonBar(totalIncome, totalExpense);
}

private void updateComparisonBar(double totalIncome, double totalExpense) {


if (totalIncome + totalExpense > 0) {
int progress = (int) ((totalIncome / (totalIncome + totalExpense)) * 100);
incomeExpenseComparisonBar.setValue(progress);
incomeExpenseComparisonBar.setString("Income: " + String.format("%.2f",
totalIncome) +
" | Expense: " + String.format("%.2f", totalExpense));
} else {
incomeExpenseComparisonBar.setValue(0);
incomeExpenseComparisonBar.setString("No data available");
}
}

private void clearIncomeFields() {


incomeDescriptionField.setText("");
incomeAmountField.setText("");
incomeDateField.setText("");
}

private void clearExpenseFields() {


expenseDescriptionField.setText("");
expenseAmountField.setText("");
expenseDateField.setText("");
}

private class ResetAllAction implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
int confirmed = JOptionPane.showConfirmDialog(ExpenseTrackerGUI.this,
"Are you sure you want to reset all data?", "Confirm Reset",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement stmt = conn.createStatement()) {
stmt.executeUpdate("DELETE FROM expenses");
} catch (SQLException ex)

{
ex.printStackTrace();
JOptionPane.showMessageDialog(ExpenseTrackerGUI.this, "Error resetting
data!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
loadRecords();
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(ExpenseTrackerGUI::new);
}
}

Output :-
Conclusion :-
The Expense Tracker application is a comprehensive tool that utilizes various
Swing components to provide a user-friendly interface for managing income and
expense.

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