Calorie Calculator in Java

Introduction

In the article, we are going to create a simple Calorie Calculator in Java with MySQL. This project can show the calorie count of certain food items that we added before. The users are able to add, edit and delete the added data and search for the calorie data of food. So, let’s get into the details.

Installation, requirements, and setting up environment

Now, let’s setup our environment:

In eclipse create a project with a suitable name. In the src folder create a package named calorieCalculator. We have to create our whole classes inside this package.

Installing MySQL connector:

Right-click on the project name and select Add External Achieves… from Build Path. Select the jar file downloaded earlier.

You are all ready to go. Let’s get into the database setup.

Project Overview: Calorie Calculator in Java with MySQL

Project Name:Calorie Calculator in Java with MySQL
AbstractIt’s a GUI-based project used with the Swing module to organize all the elements that work under the Calorie calculator.
Language/s Used:Java
IDEIntelliJ Idea Professional(Recommended)
Java version (Recommended):Java SE 18.0. 2.1
Database:MySQL
Type:Desktop Application
Recommended forFinal Year Students

MySQL setup

CREATE A DATABASE

CREATE DATABASE calculator;

USE DATABASE

USE calculator;

CREATE A TABLE

CREATE TABLE items (itemname varchar(25), calories int);

!!!DON’T FORGET TO CHANGE THE PORT, USER, AND PASSWORD IN THE PROGRAM!!!

Coding Calorie Calculator in Java

1. Main class of project

Class name: “Main.java

This module just contains the main method. This is the block that starts when we run our program. Here the main method only calls another method to display the home page.

package calorieCalculator;

import java.sql.SQLException;

public class Main {

	public static void main(String[] args) throws SQLException {
		Front.dsin();
	}

}

2. Home page

Class name: “Front.java

This module creates the homepage for the project. This homepage contains the buttons to proceed to further operations: SEARCH, ADD, EDIT. A close button is also included.

package calorieCalculator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
@SuppressWarnings("serial")
public class Front extends JFrame {
	
	public static void dsin() {
		JFrame frame = new JFrame();
		Font bt = new Font("Copperplate Gothic Bold", Font.BOLD, 20);
		JLabel x = new JLabel("X");
		x.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 30));
		x.setForeground(Color.decode("#f9d6c4"));
		x.setBounds(560, 15, 30, 30);
		frame.add(x);
		JPanel panel = new JPanel();
		panel.setBounds(558, 19, 25, 25);
		panel.setBackground(Color.decode("#2a1d1f"));
		frame.add(panel);
		JLabel c = new JLabel("C");
		c.setFont(new Font("Castellar", Font.BOLD, 80));
		c.setForeground(Color.decode("#f9d6c4"));
		c.setBounds(150, 22, 80, 80);
		frame.add(c);
		JLabel calorie = new JLabel("ALORIE");
		calorie.setFont(new Font("Castellar", Font.BOLD, 30));
		calorie.setForeground(Color.decode("#f9d6c4"));
		calorie.setBounds(215, 28, 250, 30);
		frame.add(calorie);
		JLabel calc = new JLabel("ALCULATOR");
		calc.setFont(new Font("Castellar", Font.BOLD, 30));
		calc.setForeground(Color.decode("#f9d6c4"));
		calc.setBounds(215, 60, 250, 30);
		frame.add(calc);
		JButton search = new JButton("SEARCH");
		search.setBackground(Color.decode("#f57b3d"));
		search.setForeground(Color.WHITE);
		search.setBounds(175, 150, 250, 50);
		search.setFont(bt);
		frame.add(search);
		JButton add = new JButton("ADD");
		add.setBounds(175, 250, 250, 50);
		add.setBackground(Color.decode("#f57b3d"));
		add.setForeground(Color.WHITE);
		add.setFont(bt);
		frame.add(add);
		JButton edit = new JButton("EDIT");
		edit.setBackground(Color.decode("#f57b3d"));
		edit.setForeground(Color.WHITE);
		edit.setFont(bt);
		edit.setBounds(175, 350, 250, 50);
		frame.add(edit);
		panel.addMouseListener(new MouseAdapter() {
	        @Override
	        public void mouseClicked(MouseEvent e) {
	        	frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
	        }
	    });
		
		search.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) { 
				SearchWindow.srchdsin();
			} 
		});
		
		edit.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) { 
				EditWindow.editdsin();
			} 
		});
		
		add.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) { 
				AddWindow.adddsin();
			} 
		});
		frame.setSize(600,450);
		frame.setResizable(false);
		frame.setLayout(null);
		frame.setUndecorated(true);
		frame.setLocationRelativeTo(null);  
		frame.setVisible(true);
		frame.setFocusable(true);
		frame.getContentPane().setBackground(Color.decode("#2a1d1f"));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
home page for Calorie Calculator in Java with MySQL

This is the homepage we are gonna receive as the output. The SEARCH button gets us to the page to search for the calories of food items. ADD button gets us to the page to add the food items and their calories. The EDIT button gets us to the page to edit/delete the entered food items.

3. Search page

Name: “SearchWindow.java

This module here creates the search page. It occurs when the search button from the homepage is selected. Contains a search bar to search for items and a table to get results.

Change the port, user, and password with yours.

package calorieCalculator;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class SearchWindow {
	
	private static DefaultTableModel model;
	
	public static void srchdsin() {
		JFrame frame = new JFrame();
		Font txt = new Font("Copperplate Gothic Bold", Font.PLAIN, 18);
		Font btn = new Font("Copperplate Gothic Bold", Font.BOLD, 20);
		JLabel back = new JLabel("<  BACK");
		back.setFont(btn);
		back.setForeground(Color.decode("#f9d6c4"));
		back.setBounds(25, 20, 100, 30);
		frame.add(back);
		JPanel panel = new JPanel();
		panel.setBounds(22, 23, 95, 25);
		panel.setBackground(Color.decode("#2a1d1f"));
		frame.add(panel);
		JLabel c = new JLabel("C");
		c.setFont(new Font("Castellar", Font.BOLD, 80));
		c.setForeground(Color.decode("#f9d6c4"));
		c.setBounds(150, 22, 80, 80);
		frame.add(c);
		JLabel alorie = new JLabel("ALORIE");
		alorie.setFont(new Font("Castellar", Font.BOLD, 30));
		alorie.setForeground(Color.decode("#f9d6c4"));
		alorie.setBounds(215, 28, 250, 30);
		frame.add(alorie);
		JLabel calc = new JLabel("ALCULATOR");
		calc.setFont(new Font("Castellar", Font.BOLD, 30));
		calc.setForeground(Color.decode("#f9d6c4"));
		calc.setBounds(215, 60, 250, 30);
		frame.add(calc);
		JLabel search = new JLabel("Search : ");
		search.setBounds(50, 135, 150, 30);
		search.setForeground(Color.decode("#f9d6c4"));
		search.setFont(txt);
		frame.add(search);
		JTextField srField = new JTextField();
		srField.setBounds(150, 135, 400, 30);
		srField.setText("");
		srField.setBackground(Color.decode("#f9d6c4"));
		srField.setFont(new Font("Serif", Font.PLAIN, 15));
		frame.add(srField);     
		JTable table=new JTable();
		model = (DefaultTableModel)table.getModel();
		table.setBackground(Color.decode("#f9d6c4"));
		model.addColumn("ITEM NAME");
		model.addColumn("CALORIES");
		tblupdt("");
		table.getColumnModel().getColumn(0).setPreferredWidth(225);
		JScrollPane scPane=new JScrollPane(table);
		scPane.setBounds(50, 180, 500, 225);
		frame.add(scPane);
		panel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				Front.dsin();
			}
		});
		
		srField.addKeyListener(new KeyAdapter() {
		      public void keyReleased(KeyEvent e) {
		        JTextField textField = (JTextField) e.getSource();
		        String text = textField.getText();
		        tblupdt(text);
		      }

		      public void keyTyped(KeyEvent e) {
		      }

		      public void keyPressed(KeyEvent e) {
		      }
		    });
		frame.setSize(600,450);
		frame.setResizable(false);
		frame.setLayout(null);
		frame.setUndecorated(true);
		frame.setLocationRelativeTo(null);  
		frame.setVisible(true);
		frame.setFocusable(true);
		frame.getContentPane().setBackground(Color.decode("#2a1d1f"));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void tblupdt(String str) {
		try {
			ResultSet res = dbSearch(str);
			int rowCount = model.getRowCount();
			int i;
			for (i = rowCount - 1; i >= 0; i--)
			    model.removeRow(i);
			for(i=0; res.next(); i++) {
				model.addRow(new Object[0]);
		        model.setValueAt(res.getString("itemname"), i, 0);
		        model.setValueAt(res.getInt("calories"), i, 1);
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	}
	
	public static ResultSet dbSearch(String name) throws SQLException {
		//ENTER PORT, USER, PASSWORD.
		String str1 = "SELECT * FROM items WHERE itemname like '%" +name +"%'";
		String url = "jdbc:mysql://localhost:port/calculator";
		String user = "user";
		String pass = "pass";
		Connection con = DriverManager.getConnection(url, user, pass);
		Statement stm = con.createStatement();
		ResultSet rst = stm.executeQuery(str1);
		return rst;
	}
}
search page

This is the search page when opened. The table shows the details of all items on start. If searched the table will be shown as the result of the search.

search result

4. Window to add a new item

Name: “AddWindow.java

This piece of code of Calorie Calculator in Java with MySQL here creates an interface to add the items to the database. These items are later retrieved on the search menu.

Change the port, user, and password with yours.

package calorieCalculator;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import java.sql.*;

@SuppressWarnings("serial")
public class AddWindow extends JFrame{
	
	public static void adddsin() {
		JFrame frame = new JFrame();
		Font txt = new Font("Copperplate Gothic Bold", Font.PLAIN, 18);
		Font btn = new Font("Copperplate Gothic Bold", Font.BOLD, 20);
		JLabel back = new JLabel("<  BACK");
		back.setFont(btn);
		back.setForeground(Color.decode("#f9d6c4"));
		back.setBounds(25, 20, 100, 30);
		frame.add(back);
		JPanel panel = new JPanel();
		panel.setBounds(22, 23, 95, 25);
		panel.setBackground(Color.decode("#2a1d1f"));
		frame.add(panel);
		JLabel c = new JLabel("C");
		c.setFont(new Font("Castellar", Font.BOLD, 80));
		c.setForeground(Color.decode("#f9d6c4"));
		c.setBounds(150, 22, 80, 80);
		frame.add(c);
		JLabel alorie = new JLabel("ALORIE");
		alorie.setFont(new Font("Castellar", Font.BOLD, 30));
		alorie.setForeground(Color.decode("#f9d6c4"));
		alorie.setBounds(215, 28, 250, 30);
		frame.add(alorie);
		JLabel calc = new JLabel("ALCULATOR");
		calc.setFont(new Font("Castellar", Font.BOLD, 30));
		calc.setForeground(Color.decode("#f9d6c4"));
		calc.setBounds(215, 60, 250, 30);
		frame.add(calc);
		JLabel name = new JLabel("Item Name : ");
		name.setBounds(50, 135, 150, 30);
		name.setForeground(Color.decode("#f9d6c4"));
		name.setFont(txt);
		frame.add(name);
		JTextField nmField = new JTextField();
		nmField.setBounds(50, 175, 500, 30);
		nmField.setBackground(Color.decode("#f9d6c4"));
		nmField.setFont(new Font("Serif", Font.PLAIN, 15));
		frame.add(nmField);
		JLabel calorie = new JLabel("Calorie : ");
		calorie.setBounds(50, 235, 150, 30);
		calorie.setForeground(Color.decode("#f9d6c4"));
		calorie.setFont(txt);
		frame.add(calorie);
		JTextField crField = new JTextField();
		crField.setBounds(50, 275, 200, 30);
		crField.setBackground(Color.decode("#f9d6c4"));
		crField.setFont(new Font("Serif", Font.PLAIN, 15));
		frame.add(crField);
		JButton submit = new JButton("SUBMIT");
		submit.setBounds(75, 350, 200, 50);
		submit.setBackground(Color.decode("#f57b3d"));
		submit.setForeground(Color.WHITE);
		submit.setFont(btn);
		frame.add(submit);
		JButton clear = new JButton("CLEAR");
		clear.setBounds(325, 350, 200, 50);
		clear.setBackground(Color.decode("#f57b3d"));
		clear.setForeground(Color.WHITE);
		clear.setFont(btn);
		frame.add(clear);
		panel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				Front.dsin();
			}
		});
		
		clear.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) { 
				nmField.setText("");
				crField.setText("");
			} 
		});
		
		submit.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) { 
				try {
					dbManage(nmField.getText(), Integer.parseInt(crField.getText()));
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				nmField.setText("");
				crField.setText("");
				nmField.requestFocus();
			} 
		});
		frame.setSize(600,450);
		frame.setResizable(false);
		frame.setLayout(null);
		frame.setUndecorated(true);
		frame.setLocationRelativeTo(null);  
		frame.setVisible(true);
		frame.setFocusable(true);
		frame.getContentPane().setBackground(Color.decode("#2a1d1f"));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void dbManage(String str, int cal) throws SQLException {
		//ENTER PORT, USER, PASSWORD.
		String str1 = "INSERT INTO items VALUES('"+str+"', "+cal+")";
		String url = "jdbc:mysql://localhost:port/calculator";
		String user = "user";
		String pass = "password";
		Connection con = DriverManager.getConnection(url, user, pass);
		Statement stm = con.createStatement();
		stm.executeUpdate(str1);
		System.out.println(str1+";");
		con.close();
	}
}
add new item

Here we can add an item with the item name and calories of a food product.

5. Window to edit old items

Name: “EditWindow.java

This code of Calorie Calculator in Java with MySQL helps us to make an interface to edit and delete data in the database. Contains different buttons for edit and deleting along with a text field for item names and calories.

Change the port, user, and password with yours.

package calorieCalculator;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class EditWindow {
	public static void editdsin() {
		JFrame frame = new JFrame();
		Font txt = new Font("Copperplate Gothic Bold", Font.PLAIN, 18);
		Font btn = new Font("Copperplate Gothic Bold", Font.BOLD, 20);
		JLabel back = new JLabel("<  BACK");
		back.setFont(btn);
		back.setForeground(Color.decode("#f9d6c4"));
		back.setBounds(25, 20, 100, 30);
		frame.add(back);
		JPanel panel = new JPanel();
		panel.setBounds(22, 23, 95, 25);
		panel.setBackground(Color.decode("#2a1d1f"));
		frame.add(panel);
		JLabel c = new JLabel("C");
		c.setFont(new Font("Castellar", Font.BOLD, 80));
		c.setForeground(Color.decode("#f9d6c4"));
		c.setBounds(150, 22, 80, 80);
		frame.add(c);
		JLabel alorie = new JLabel("ALORIE");
		alorie.setFont(new Font("Castellar", Font.BOLD, 30));
		alorie.setForeground(Color.decode("#f9d6c4"));
		alorie.setBounds(215, 28, 250, 30);
		frame.add(alorie);
		JLabel calc = new JLabel("ALCULATOR");
		calc.setFont(new Font("Castellar", Font.BOLD, 30));
		calc.setForeground(Color.decode("#f9d6c4"));
		calc.setBounds(215, 60, 250, 30);
		frame.add(calc);
		JLabel name = new JLabel("Item Name : ");
		name.setBounds(50, 135, 150, 30);
		name.setForeground(Color.decode("#f9d6c4"));
		name.setFont(txt);
		frame.add(name);
		JTextField nmField = new JTextField();
		nmField.setBounds(50, 175, 500, 30);
		nmField.setBackground(Color.decode("#f9d6c4"));
		nmField.setFont(new Font("Serif", Font.PLAIN, 15));
		frame.add(nmField);
		JLabel calorie = new JLabel("Calorie : ");
		calorie.setBounds(50, 235, 150, 30);
		calorie.setForeground(Color.decode("#f9d6c4"));
		calorie.setFont(txt);
		frame.add(calorie);
		JTextField crField = new JTextField();
		crField.setBounds(50, 275, 200, 30);
		crField.setBackground(Color.decode("#f9d6c4"));
		crField.setFont(new Font("Serif", Font.PLAIN, 15));
		frame.add(crField);
		JButton dt = new JButton("EDIT");
		dt.setBounds(75, 350, 200, 50);
		dt.setBackground(Color.decode("#f57b3d"));
		dt.setForeground(Color.WHITE);
		dt.setFont(btn);
		frame.add(dt);
		JButton dlt = new JButton("DELETE");
		dlt.setBounds(325, 350, 200, 50);
		dlt.setBackground(Color.decode("#f57b3d"));
		dlt.setForeground(Color.WHITE);
		dlt.setFont(btn);
		frame.add(dlt);
		JLabel wrng = new JLabel("!!CHANGES ONCE MADE CANNOT BE REVERTED!!");
		wrng.setBounds(45, 410, 550, 30);
		wrng.setForeground(Color.RED);
		wrng.setFont(txt);
		frame.add(wrng);
		panel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				Front.dsin();
			}
		});
		
		dt.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) { 
				try {
					dbEdit(nmField.getText(), Integer.parseInt(crField.getText()));
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				nmField.setText("");
				crField.setText("");
			} 
		});
		
		dlt.addActionListener(new ActionListener() { 
			public void actionPerformed(ActionEvent e) { 
				try {
					dbDelete(nmField.getText());
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
				nmField.setText("");
				crField.setText("");
			} 
		});
		frame.setSize(600,450);
		frame.setResizable(false);
		frame.setLayout(null);
		frame.setUndecorated(true);
		frame.setLocationRelativeTo(null);  
		frame.setVisible(true);
		frame.setFocusable(true);
		frame.getContentPane().setBackground(Color.decode("#2a1d1f"));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void dbDelete(String name) throws SQLException {
		//ENTER PORT, USER, PASSWORD.
		String str1 = "DELETE FROM items WHERE itemname = '"+name+"'";
		String url = "jdbc:mysql://localhost:port/calculator";
		String user = "user";
		String pass = "password";
		Connection con = DriverManager.getConnection(url, user, pass);
		Statement stm = con.createStatement();
		stm.executeUpdate(str1);
		con.close();
	}
	
	public static void dbEdit(String name, int calorie) throws SQLException {
		//ENTER PORT, USER, PASSWORD.
		String str1 = "UPDATE items SET calories = " + calorie+ " WHERE itemname = '"+ name+ "'";
		String url = "jdbc:mysql://localhost:port/calculator";
		String user = "user";
		String pass = "password";
		Connection con = DriverManager.getConnection(url, user, pass);
		Statement stm = con.createStatement();
		stm.executeUpdate(str1);
		con.close();
	}
}

The interface will be as shown below:

edit old items

The final output for Calorie Calculator in Java

The following video is the result and how to use the program:


Also Read:

Share:

Author: Ayush Purawr