ATM Interface GUI Project for Beginners – Full Tutorial

 ATM Machine GUI Project

ATM Machine GUI Project


Project Structure:

You are required to implement an ATM machine simulation with a graphical user interface (GUI). The requirements are as follows:

You are required to implement an ATM machine simulation with a graphical user interface (GUI). The requirements are as follows


Classes:

  1. Main GUI Class:

    • Hand-code the GUI (do not use any GUI generators).

    • Must include:

      • A main method.

      • A constructor that builds the GUI.

      • Event handlers for each of the four buttons: Withdraw, Deposit, Transfer, Balance.

    • Withdraw button:

      • Check if the value in the text field is numeric.

      • Ensure the amount is in increments of $20.

      • Attempt to withdraw the amount from the selected account (Checking or Savings).

      • Handle exceptions for insufficient funds.

      • If any error occurs (non-numeric, wrong increment, insufficient funds), display an error message using JOptionPane.

      • If successful, show a confirmation message.

    • Deposit button:

      • Only check if the amount is numeric.

      • Deposit the amount in the selected account.

    • Transfer button:

      • Check if the amount is numeric.

      • Ensure there are sufficient funds to transfer from the source account.

      • Transfer funds from one account to the other.

    • Balance button:

      • Show the current balance in the selected account using JOptionPane.

    • The main class must create two Account objects: one for Checking and one for Savings.

  2. Account Class:

    • Should have:

      • A constructor.

      • Methods corresponding to each of the four GUI buttons.

      • Logic to deduct a $1.50 service charge after more than four withdrawals from either account combined.

      • The withdraw method should throw an InsufficientFunds exception if there is not enough balance (including the service charge when it applies).

  3. InsufficientFunds Class:

    • A user-defined checked exception.

Coding Style Guidelines:

  • Make all variables private.

  • Name all constants.

  • Avoid code duplication.

  • Test the program with different scenarios.


 the Answer

1. Main Class (ATM GUI) Explanation

  • Purpose: Handles the user interface and user actions.

  • How it works:

    • Users select the account (Checking/Savings) using radio buttons.

    • They enter an amount in the text field and choose an action by clicking a button.

    • Each button has an event handler that performs checks and calls methods in the Account class.

    • Results and errors are shown using dialog boxes (JOptionPane).

2. Account Class Explanation

  • Purpose: Models a bank account (Checking or Savings).

  • Functions:

    • Methods to withdraw, deposit, transfer, and get the balance.

    • Keeps track of total withdrawals (across both accounts).

    • After 4 withdrawals, applies a $1.50 service charge for every further withdrawal.

    • Throws a custom exception if trying to withdraw more than the available balance (including the service fee if applicable).

3. InsufficientFunds Exception Explanation

  • Purpose: Handles cases where the account does not have enough funds for the requested operation.

  • How it works:

    • When a withdrawal/transfer is attempted and there isn’t enough money, this exception is thrown.

    • The GUI catches the exception and shows an error message.


Start with an overview:

  1. "This project simulates an ATM using a Java GUI, with separate classes for the GUI, account logic, and custom exception handling."

  2. Show the main features and user flow:

    • Explain how the user interacts with the GUI.

    • Describe what happens when each button is clicked, focusing on validation and feedback.

  3. Describe the Account logic:

    • Mention the service charge rule.

    • Explain how methods are separated for each operation.

  4. Custom Exception:

    • Explain why and how you used a custom exception for insufficient funds.

  5. Testing:

    • List a few scenarios you tested: e.g., trying to withdraw more than available, withdrawing in wrong increments, testing service charges after 4 withdrawals, etc.

  6. Good practices:

    • Highlight the use of private variables, constants, and avoiding duplicate code.



1. InsufficientFunds.java

java
// User-defined checked exception public class InsufficientFunds extends Exception { public InsufficientFunds(String message) { super(message); } }




2. Account.java

java
public class Account { private double balance; private int withdrawals; private static int totalWithdrawals = 0; private static final int FREE_WITHDRAWALS = 4; private static final double SERVICE_CHARGE = 1.5; public Account(double initialBalance) { this.balance = initialBalance; this.withdrawals = 0; } public double getBalance() { return balance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFunds { boolean chargeFee = (totalWithdrawals >= FREE_WITHDRAWALS); double totalAmount = amount + (chargeFee ? SERVICE_CHARGE : 0); if (amount <= 0 || amount % 20 != 0) { throw new InsufficientFunds("Withdrawal must be in increments of $20."); } if (balance < totalAmount) { throw new InsufficientFunds("Insufficient funds for this withdrawal."); } balance -= amount; if (chargeFee) { balance -= SERVICE_CHARGE; } withdrawals++; totalWithdrawals++; } public void transferTo(Account other, double amount) throws InsufficientFunds { boolean chargeFee = (totalWithdrawals >= FREE_WITHDRAWALS); double totalAmount = amount + (chargeFee ? SERVICE_CHARGE : 0); if (balance < totalAmount) { throw new InsufficientFunds("Insufficient funds to transfer."); } this.withdraw(amount); // Handles incrementing the withdrawal counters & service charge other.deposit(amount); } }

3. ATMGui.java

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ATMGui extends JFrame { private Account checking; private Account savings; private JTextField amountField; private JRadioButton checkingBtn, savingsBtn; public ATMGui() { // Initialize accounts checking = new Account(1000); savings = new Account(1000); // Set up frame setTitle("ATM Machine"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(350, 250); setLocationRelativeTo(null); // Components amountField = new JTextField(10); checkingBtn = new JRadioButton("Checking", true); savingsBtn = new JRadioButton("Savings"); ButtonGroup group = new ButtonGroup(); group.add(checkingBtn); group.add(savingsBtn); JButton withdrawBtn = new JButton("Withdraw"); JButton depositBtn = new JButton("Deposit"); JButton transferBtn = new JButton("Transfer"); JButton balanceBtn = new JButton("Balance"); // Panel setup JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); // Amount field gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; panel.add(new JLabel("Amount:"), gbc); gbc.gridx = 2; gbc.gridwidth = 2; panel.add(amountField, gbc); // Account selection gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; panel.add(checkingBtn, gbc); gbc.gridx = 1; panel.add(savingsBtn, gbc); // Buttons gbc.gridx = 0; gbc.gridy = 2; panel.add(withdrawBtn, gbc); gbc.gridx = 1; panel.add(depositBtn, gbc); gbc.gridx = 2; panel.add(transferBtn, gbc); gbc.gridx = 3; panel.add(balanceBtn, gbc); add(panel); // Button Listeners withdrawBtn.addActionListener(e -> handleWithdraw()); depositBtn.addActionListener(e -> handleDeposit()); transferBtn.addActionListener(e -> handleTransfer()); balanceBtn.addActionListener(e -> handleBalance()); } private Account getSelectedAccount() { return checkingBtn.isSelected() ? checking : savings; } private Account getOtherAccount() { return checkingBtn.isSelected() ? savings : checking; } private void handleWithdraw() { try { double amount = Double.parseDouble(amountField.getText()); Account selected = getSelectedAccount(); if (amount % 20 != 0) { throw new NumberFormatException("Amount must be in increments of $20."); } selected.withdraw(amount); JOptionPane.showMessageDialog(this, "Withdrawal successful!"); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, "Enter a valid numeric amount in increments of $20.", "Input Error", JOptionPane.ERROR_MESSAGE); } catch (InsufficientFunds ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), "Insufficient Funds", JOptionPane.ERROR_MESSAGE); } } private void handleDeposit() { try { double amount = Double.parseDouble(amountField.getText()); if (amount <= 0) throw new NumberFormatException(); Account selected = getSelectedAccount(); selected.deposit(amount); JOptionPane.showMessageDialog(this, "Deposit successful!"); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, "Enter a valid numeric amount.", "Input Error", JOptionPane.ERROR_MESSAGE); } } private void handleTransfer() { try { double amount = Double.parseDouble(amountField.getText()); if (amount <= 0) throw new NumberFormatException(); Account from = getSelectedAccount(); Account to = getOtherAccount(); from.transferTo(to, amount); JOptionPane.showMessageDialog(this, "Transfer successful!"); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, "Enter a valid numeric amount.", "Input Error", JOptionPane.ERROR_MESSAGE); } catch (InsufficientFunds ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), "Insufficient Funds", JOptionPane.ERROR_MESSAGE); } } private void handleBalance() { Account selected = getSelectedAccount(); JOptionPane.showMessageDialog(this, "Current Balance: $" + String.format("%.2f", selected.getBalance())); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { new ATMGui().setVisible(true); }); } }




Summary:
The program simulates an ATM using three classes.

The user interacts with a graphical interface, performing banking operations while the program ensures all business rules and error handling are followed. All error messages and confirmations are displayed using pop-up dialogs.

The service charge is applied after four withdrawals from either account (combined). The program follows good object-oriented programming practices and clean code structure.




📩 Need a similar solution? Email me: adel455@hotmail.com



Previous Post Next Post

Comments

Nepali Graphics - Learn design, Animation, and Progrmming