JavaScript - Expense and Income Tracker with JavaScript

How to Build an Expense and Income Tracker with JavaScript


Expense and Income Tracker with JavaScript


In this Javascript tutorial, we will see how to create a web application that allows users to enter their expenses and incomes, view a list of these transactions, and calculate the total net income (income - expenses).



Project Source Code:

HTML and CSS Page


<!DOCTYPE html>
<html>
<head>
<title>Expense and Income Tracker</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
rel="stylesheet">
</head>
<body>

<div class="container">
<h1><i class="fas fa-chart-line"></i>Expense-Income Tracker</h1>
<form id="expense-form">
<label>
<i class="fas fa-file-alt"></i>Description:
<input type="text" id="description" placeholder="Enter Expense/Income Description">
</label>
<label>
<i class="fas fa-dollar-sign"></i>Amount:
<input type="number" id="amount" placeholder="Enter Expense/Income Amount">
</label>
<label>
<i class="fas fa-tags"></i>Type:
<select id="type">
<option value="expense">Expense</option>
<option value="income">Income</option>
</select>
</label>
<button type="button" id="btn-add"><i class="fas fa-plus-circle"></i>Add</button>
</form>
<div id="show-values">
<div class="box-expense">
<h2><i class="fas fa-arrow-circle-down"></i>Expense</h2>
<button class="btn" id="btn-clear-expense" style="display: none;">
<i class="fas fa-trash"></i>Clear All
</button>
<ul id="expense-list">
</ul>
</div>

<div class="box-income">
<h2><i class="fas fa-arrow-circle-up"></i>Income</h2>
<button class="btn" id="btn-clear-income" style="display: none;">
<i class="fas fa-trash"></i>Clear All
</button>
<ul id="income-list">
</ul>
</div>

<div class="box-calculate">
<h2><i class="fas fa-calculator"></i>Total Net
</h2> <span id="total"></span>
</div>
</div>

</div>



<script src="script.js"></script>



</body>
</html>



JavaScript Code


// Declare variables to store references to HTML elements
let expenseList = document.getElementById("expense-list");
let incomeList = document.getElementById("income-list");
let total = document.getElementById("total");
let expenseForm = document.getElementById("expense-form");
let description = document.getElementById("description");
let amount = document.getElementById("amount");
let type = document.getElementById("type");
let btnAdd = document.getElementById("btn-add");
let btnClearIncomes = document.getElementById("btn-clear-income");
let btnClearExpenses = document.getElementById("btn-clear-expense");

// Initialize arrays and variables for expenses and incomes
let expenses = [];
let incomes = [];
let totalExpenses = 0;
let totalIncomes = 0;

// Add event listener to the button add when clicked
btnAdd.addEventListener("click", function(){

// Create an object to represent the expense / income
let dataValues = { description:description.value,
amount: parseFloat(amount.value),
type:type.value
};

// If the expense / income has a description and amount, add it to the appropriate array
if(dataValues.description && dataValues.amount){

if(dataValues.type === "expense"){
expenses.push(dataValues);
totalExpenses += dataValues.amount;
}
else
{
incomes.push(dataValues);
totalIncomes += dataValues.amount;
}

// Clear the description and amount input fields, then update the lists and total
description.value = "";
amount.value = "";
updateLists();
updateTotal();
}

});


// Function to update the HTML lists of expenses and incomes
function updateLists(){
// Clear the lists
expenseList.innerHTML = "";
incomeList.innerHTML = "";


/* Loop through the expenses and incomes arrays and add each one to its
respective list as an HTML <li> element */
expenses.forEach(function(expense){
let li = document.createElement("li");
li.innerHTML = expense.description + ": $" + expense.amount;
expenseList.appendChild(li);
});

incomes.forEach(function(income){
let li = document.createElement("li");
li.innerHTML = income.description + ": $" + income.amount;
incomeList.appendChild(li);
});
}

// Function to update the total income and expenses and display the result
function updateTotal()
{
total.innerHTML = "";
let netIncome = totalIncomes - totalExpenses;

/* Display the net income with a minus sign if it's negative,
otherwise display it as a positive value */
if(netIncome < 0){
total.innerHTML = "-$" + -netIncome;
}
else{
total.innerHTML = "$" + netIncome;
}


// Hide the clear buttons if there are no expenses or incomes, otherwise show them
if(expenseList.children.length == 0 ){
btnClearExpenses.style.display = "none";
}else{
btnClearExpenses.style.display = "block";
}

if(incomeList.children.length == 0 ){
btnClearIncomes.style.display = "none";
}else{
btnClearIncomes.style.display = "block";
}


}



// Add event listeners to the clear buttons for expenses and incomes
btnClearExpenses.addEventListener("click", function(){

expenses = [];
totalExpenses = 0;
updateLists();
updateTotal();

});

btnClearIncomes.addEventListener("click", function(){

incomes = [];
totalIncomes = 0;
updateLists();
updateTotal();

});





Code Explanation:

This JavaScript code enables users to manage expenses and incomes by allowing them to input financial transactions, view lists of these transactions, and calculate the net income.

This JavaScript code performs the following actions:

1 - Variable Declarations: The code declares variables to store references to HTML elements such as expense and income lists, total, form inputs, and buttons. 
It also initializes arrays and variables for tracking expenses and incomes along with their totals.

2 - Add Event Listener: An event listener is added to the "Add" button (btnAdd) for managing the addition of expenses and incomes. 
When clicked, it generates a transaction object containing a description, amount, and type, and appends it to the appropriate array (either expenses or incomes). 
It subsequently updates the lists displaying these transactions and computes the total net income.

3 - Update Lists Function: A function (updateLists()) that updates the HTML lists for expenses and incomes. It clears the existing lists and then iterates through the expenses and incomes arrays, creating list items (HTML <li> elements) for each transaction.

4 - Update Total Function: The "updateTotal()" function calculates the net income by subtracting total expenses from total income, updating the "Total Net" display with the value (formatted as positive or negative), and controlling the visibility of "Clear" buttons based on transaction presence.

5 - Clear Buttons Event Listeners: The "Clear" buttons for expenses and incomes (btnClearExpenses and btnClearIncomes) have event listeners that, upon clicking, clear the corresponding arrays, reset the totals for expenses and incomes, and update the HTML lists and total net income.



OUTPUT:

Build an Expense and Income Tracker with JavaScript

JavaScript Expenses And Incomes Tracker App Source Code

if you want to download the project files click on the button below


download the source code








Java - Images Gallery Project In Netbeans

How to Create Image Gallery in Java NetBeans

How to Create Image Gallery in Java NetBeans


In this Java Long Tutorial we will see how How To Create an images gallery application using Java Swing in Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Loaded Images from a specified directory (in this code, "C:\images"), and add the supported image files (with extensions such as jpg, jpeg, png, and gif) to the list of images.
- Displayed the selected image in in the image view.
- Navigate through the images using the "Previous" and "Next" buttons.
- Search for specific images by entering a search term in the text field, which filters the list to display matching image names.




Project Source Code:


package imagesgalleryapp;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 *
 * @author 1BestCsharp
 */

public class ImagesGalleryApp extends JFrame {

    private DefaultListModel<ImageInfo> imageListModel;
    private JList<ImageInfo> imageList;
    private JLabel imageView;
    private JButton prevButton;
    private JButton nextButton;
    private JTextField searchField;
    private List<ImageInfo> images;
    
    public ImagesGalleryApp(){
        try
        {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        
        setTitle("Image Gallery");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800,600);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        images = new ArrayList<>();
        imageListModel = new DefaultListModel<>();
        initialize(); // initialize the user interface
        
    }
    
    // create a method to initialize the user interface
    private void initialize()
    {
        // Create a list to display image names
        imageList = new JList<>(imageListModel);
        imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        imageList.addListSelectionListener(e->displaySelectedImage());
        
        // Display selected image
        imageView = new JLabel();
        imageView.setHorizontalAlignment(JLabel.CENTER);
        
        // Previous & Next buttons to navigate images
        prevButton = new JButton("Previous");
        prevButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                navigateImage(-1);
                
            }
        });
        
        nextButton = new JButton("Next");
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                navigateImage(1);
                
            }
        });
        
        // Search field to filter images by name
        searchField = new JTextField(20);
        searchField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
             
                searchImage(searchField.getText());
                
            }
        });
        
        // Create top panel containing search field
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        topPanel.add(new JLabel("Search"));
        topPanel.add(searchField);
        
        // Create center panel with list and image view
        JPanel centerPanel = new JPanel(new GridLayout(1, 2));
        centerPanel.add(new JScrollPane(imageList));
        centerPanel.add(imageView);
        
        // Create bottom panel with navigation buttons
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        bottomPanel.add(prevButton);
        bottomPanel.add(nextButton);
        
        // Add panels to the main frame
        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
        
    }
    
    
    
    
    // Create Class to store image information
    private class ImageInfo{
        
        private String filePath;
        private String name;
        
        public ImageInfo(String filePath, String name)
        {
            this.filePath = filePath;
            this.name = name;
        }
        
        @Override
        public String toString(){ return name; }
        
    }
    
    
    // Create a Function to Navigate through images
    private void navigateImage(int offset)
    {
        int selectedIndex = imageList.getSelectedIndex();
        if(selectedIndex >= 0)
        {
            int newIndex = (selectedIndex + offset + images.size()) % images.size();
            imageList.setSelectedIndex(newIndex);
            displaySelectedImage();
        }
    }
    
    
    
    
    
    // Create a Function to Search images based on the provided search term
    private void searchImage(String searchTerm)
    {
        imageListModel.clear();
        for(ImageInfo image : images)
        {
            if(image.name.toLowerCase().contains(searchTerm.toLowerCase()))
            {
                imageListModel.addElement(image);
            }
        }
        displaySelectedImage();
    }
    
    
    
    // Create a Function to Display selected image in the image view
    public void displaySelectedImage()
    {
        ImageInfo selectedImage = imageList.getSelectedValue();
        if(selectedImage != null)
        {
            ImageIcon imageIcon = new ImageIcon(selectedImage.filePath);
            Image scaledImage = imageIcon.getImage().getScaledInstance(imageView.getWidth(), imageView.getHeight(), Image.SCALE_SMOOTH);
            imageView.setIcon(new ImageIcon(scaledImage));
        }
    }
    
    

    // Create a Function to Load images from a specified directory
    private void loadImagesFromDirectory(String directoryPath)
    {
        File directory = new File(directoryPath);
        if(directory.isDirectory())
        {
            File[] imageFiles = directory.listFiles( 
                    file->file.isFile() && isSupported(file.getName()) );
            if(imageFiles != null)
            {
                for(File imageFile: imageFiles)
                {
                    images.add(new ImageInfo(imageFile.getAbsolutePath(), imageFile.getName()));
                    imageListModel.addElement(new ImageInfo(imageFile.getAbsolutePath(), imageFile.getName()));
                }
            }
        }
    }
    
    // Create a Function to Check if a file has a supported image extension
    private boolean isSupported(String fileName)
    {
        String[] supportedExtensions = {"jpg","jpeg","png","gif"};
        String extension = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        
        for(String ext : supportedExtensions)
        {
            if(extension.equals(ext))
            {
                return true;
            }
        }
        
        return false;
    }
    
    
    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(()->{
        
            ImagesGalleryApp app = new ImagesGalleryApp();
            app.loadImagesFromDirectory("C:\\images");
            app.setVisible(true);
            
        });
        
        
    }

}




The Final Result:



Java Image Gallery 1

Java Image Gallery 2

Java Image Gallery 3

Java Image Gallery 4





if you want to download the project files click on the button below

download the source code