Adding DB backend to a small Java program

Hi all,

first off I want to say this is a really cool learning tool. Now, I have been passing this java program around to help me learn from it the java language. I am a novice myself. I would like to know what changes would have to be made to have the java program interact with a small MS Access or MySQL database for functions such as:

1. Verifying a pin number
2. Checking balance
3. Making a withdrawal (check to see sufficient funds & update records)
4. Making a deposit (update records)

Stuff like that. Really only a three table DB will suffice:

1. User table
2. Account table
3. User_Account Table (for transactions)

All I am looking for is some direction on how to implement this in future days/weeks as I play with this program to learn.

Here is the code I have been playing around with:

// import libraries that are needed for this application. You can get more insight by viewing the javadoc (google: java class-name-here)
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;

//This class defines one field in a record

public class ATM extends Applet
{
// when applet is started, this is called automatically by the applet super class
    public void init()
    {
        // add panel to applet - the ATMPanel.

         add(new ATMPanel());
    }

    static class ATMPanel extends Panel
    {
           // setting up a pin that is needed for the atm
            private static String PIN= "3602";
         private int accountmoney = 3400;
         //constants that provide state information for the atm
         private static final int WAIT_FOR_CARD = 1;
         private static final int WAIT_FOR_PIN = 2;
         private static final int MENU_DISPLAYED = 3;
         private static final int TRANSFER_MONEY = 4;
         private static final int DISBURSE_MONEY = 5;
         private static final int CHECK_BALANCE = 6;

         // text area that most likely contains the output from the ATM. Look up on google 'java TextArea' to view javadoc.
         private TextArea mScreen=
              new TextArea("", 6, 45, TextArea.SCROLLBARS_NONE);

         // some buttons
         private Button mEnter= new Button("Enter");
         private Button mClear= new Button("Clear");
         private Button mCancel= new Button("Cancel");

         private JButton Receipt = new JButton("Receipts Slot");
         private Button Quit = new Button("Quit");
           private JButton Cash = new JButton("Cash Slot");

           private JLabel something = new JLabel("Yeah");

         private String mPin= "";
         private String Transfer= "";
         private int Transfer1;
         private int state = WAIT_FOR_CARD; // the current state of the ATM

         public ATMPanel()
         {
 // set  the graphical layout for the applet.
              setLayout(new BorderLayout());
// dont allow the text area to be editable
              mScreen.setEditable(false);

// a listener that acts as a callback function for the keypad. when the keypad is pressed, this is called
              ActionListener keyPadListener = new ActionListener()
              {
                   public void actionPerformed(ActionEvent e)
                   {
                        key(Integer.parseInt(((Button) e.getSource()).getLabel()));
                   }
              };

            // create keypad with 10 buttons

              JPanel keypad= new JPanel(new GridLayout(0,3));
              for(int i=1; i<10; i++)
              {
                   Button btn= new Button(String.valueOf(i));

                    // add keyPadListener as action listener to each button, the listener will get called when a button is pressed
                   btn.addActionListener(keyPadListener);
                   keypad.add(btn);
              }

              keypad.add(new Label());
              Button btn= new Button("0");
              btn.addActionListener(keyPadListener);
              keypad.add(btn);

// what to do when the enter button is clicked
              mEnter.addActionListener(new ActionListener()
              {
                   public void actionPerformed(ActionEvent e)
                   {
// call the method enter() when enter is pressed.
                            enter();
                       }
                });

// see enter() - same idea
              mClear.addActionListener(new ActionListener()
              {
                   public void actionPerformed(ActionEvent e)
                   {
                            clear();
                       }
                });
// same idea as enter()
              mCancel.addActionListener(new ActionListener()
              {
                   public void actionPerformed(ActionEvent e)
                   {
                            cancel();
                       }
                 });
// same idea as enter()
                 Receipt.addActionListener(new ActionListener()
                 {
                      public void actionPerformed(ActionEvent e)
                      {
                               receipt();
                       }
                 });
// same idea as enter()
                 Quit.addActionListener(new ActionListener()
                 {
                      public void actionPerformed(ActionEvent e)
                      {
                           quit();
                      }
                 });
// same idea as enter()
                 Cash.addActionListener(new ActionListener()
                 {
                      public void actionPerformed(ActionEvent e)
                      {
                               cash();
                         }
                 });

               // add enter, clear, receeipt, quit, and cancel buttons to panel

                 Panel controls= new Panel(new GridLayout(2,3));
              controls.add(mEnter);
              controls.add(mClear);
              controls.add(mCancel);

                 controls.add(Receipt);
                 controls.add(Quit);
              controls.add(Cash);

              add("North",  mScreen);
              add("Center", keypad);
              add("South",   controls);

              mScreen.setText("Enter your card and press a number key.");
         }

// the logic of what to do for various states of the atm when keys are pressed.
         private void key(int key)
         {
             // called (by action listener) whenever a number button is pressed
// switch statement - look it up on google. basically same as an if, else if ... else statement
             switch (state)
             {
                 case WAIT_FOR_CARD:     // waiting for card

                       // clear screen, and ask user to enter pin

                       clear();
                       mScreen.setText(
                            "Card accepted.\n" +
                            "Good evening Mr Singh.\n" +
                            "Please enter your pin...");
                       state = WAIT_FOR_PIN;
                       break;
                 case WAIT_FOR_PIN:      // waiting for pin

                      // accept number as part of pin

                      if (mPin.length() == 0)
                             mScreen.setText("");
                                mPin += String.valueOf(key);
                                mScreen.setText(mScreen.getText() +"*");
                      break;
                 case MENU_DISPLAYED:

                      // treat number as menu selection

                      switch(key)
                      {
                           case 1:
                             TransMoney();
                                break;
                           case 2:
                             DispenseMoney();
                                break;
                           case 3:
                             CheckBalance();
                                break;
                           default:
                             InvalidOption();
                      }
                      break;
                 case TRANSFER_MONEY:
                           // treat number as part of amount to transfer

                           if(Transfer.length() == 0)
                               mScreen.setText("");
                               Transfer += String.valueOf(key);
                               mScreen.setText(mScreen.getText() + key );

                          break;
                 case DISBURSE_MONEY:
                           // treat number as part of amount to disburse
                          if(Transfer.length() == 0)
                                  mScreen.setText("");
                                  Transfer += String.valueOf(key);
                                mScreen.setText(mScreen.getText() + key );

                           break;
                 case CHECK_BALANCE:
                           break;
              }
         }

            // called (by action listener) whenever a enter button is pressed

// what to do when enter is pressed according to various states of the ATM - could have been a switch statement like key()
         private void enter()
         {
           if (state == WAIT_FOR_CARD)
              return;

           if (state == WAIT_FOR_PIN)
           {
              // check pin

              if (mPin.equals(PIN))
              {
                  // pin correct, display menu
                  menu();
              }
              else
              {
                  // pin incorrect, display message
                  clear();
                  mScreen.setText("Invalid pin, try again (it's " +PIN +")");
              }
           }

           if (state == TRANSFER_MONEY)
           {
                  // perform transfer

                    Transfer1 = Integer.parseInt(Transfer);
                    accountmoney += Transfer1;

                Transfer = "";
                Transfer1 = 0;
                menu();
           }

           if (state == DISBURSE_MONEY)
           {
                // perform disburse

                Transfer1 = Integer.parseInt(Transfer);
                accountmoney -= Transfer1;

                    Transfer = "";
                    Transfer1 = 0;
                menu();
           }
         }

             // called (by action listener) whenever clear button is pressed

        private void clear()
         {
              if (state == WAIT_FOR_CARD)
                   return;

              if (state == WAIT_FOR_PIN)
              {
                   mScreen.setText("");
                   mPin= "";
              }
         }

             // called (by action listener) whenever cancel button is pressed

        private void cancel()
         {
              menu();
         }

         private void menu()
         {
                // display menu

               state = MENU_DISPLAYED;
              clear();
              mScreen.setText(
                   "1. Transfer money\n" +
                   "2. Dispense money\n" +
                   "3. Check balance");
         }

             // called (by action listener) whenever receipt button is pressed

        private void receipt()
          {
                 // display popuup
                 JOptionPane.showMessageDialog(null, new javax.swing.ImageIcon("receipt.jpg"));
              }

              // called (by action listener) whenever cash button is pressed

            private void cash()
              {
                 // display popuup

                JOptionPane.showMessageDialog(null, new javax.swing.ImageIcon("money.jpg"));
            }

              // called (by action listener) whenever quit button is pressed

          private void quit()
            {
                // quit application

                System.exit(0);
           }

         private void TransMoney()
         {
              clear();
                 mScreen.setText("How much money would you like to transfer? ...");
              state = TRANSFER_MONEY;
         }

         private void DispenseMoney()
         {
              clear();
              mScreen.setText("How much money would you like to take out? ...");
             
              if (Transfer1 > accountmoney)
                 {
                      mScreen.setText("You can't have more money than you already have");
                 }

              state = DISBURSE_MONEY;
         }

         private void CheckBalance()
         {
              state = CHECK_BALANCE;
              clear();
              mScreen.setText("This is the amount of money u have in your account.\n" +
                                  " ---> " + "$"+ accountmoney);
         }

         private void InvalidOption()
         {
              clear();
              mScreen.setText("You have choose the incorrect option. Try again");
         }
    }


// the main method that creates a frame, and adds your panel to it so that you can see it.
    public static void main(String[] argv)
    {
         Frame frame= new Frame("ATM");
         frame.add(new ATMPanel());
         frame.pack();
         frame.setResizable(false);
         frame.setVisible(true);
// what should happen when you close the window? if this is absent, basically the window disappears but the program is still running.
         frame.addWindowListener(new WindowAdapter()
         {
              public void windowClosing(WindowEvent e)
              {
                      System.exit(0);
                 }
           });
    }
}

// what else do you want. the program is nicely laid out so that the logic is readable.
marcoullispAsked:
Who is Participating?
 
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
http://www.java2s.com/Code/Java/Database-SQL-JDBC/Database-Swing-Applet.htm

checkout the above link to see how to connect to the DB from applet.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
You probably need to do some validation on the PIN number and ATM card number. You can store them in a data-base back-end and then query for the same. Have a look at:

http://java.sun.com/docs/books/tutorial/jdbc/

http://www.javaalmanac.com/egs/java.sql/pkg.html
0
 
marcoullispAuthor Commented:
Um... can I have something a little more than a link to follow... how about something specific to the program in question...

:-)

PKM
0
 
Tommy BraasCommented:
A popular pattern is Data Access Objects, or DAOs, with their corresponding Data Objects, or DOs.

Create one DAO for each data structure (or table) you need to access. For instance UserDAO, AccountDAO and TransactionDAO.

Each DAO will provide data objects corresponding to the DAO, so the UserDAO would provide User data objects.

A DAO would contain methods such as: insert, delete, update, findById and findAll. Each method abstracts the actual data access.

If you are bent on using a SQL database, you will have to learn SQL and JDBC. To start with I would recommend using POJOs (Plain Old Java Object) to iron out any logic flaws.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
There are many samples at: >> http://www.javaalmanac.com/egs/java.sql/pkg.html

as to how to make connections, execute queries, etc. In your case, you first need to define your table structure in the DB. Once that is done, we can help with the queries. What information do you want to hold in your tables?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.