Results 1 to 18 of 18
  1. #1
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default Exception occurred during event dispatching: java.lang.NullPointerException

    Hello to all!!!

    Can anibody help me with this problem, i'm getting a null pointer exception in this part of the code:

    -----------------------------------------------------------------------
    public boolean findBranch(Integer iddespesa)
    {

    try
    {
    con = AccessConection.getInstance().getConnection();
    ps = con.prepareStatement("SELECT iddespesa FROM despesas where iddespesa = ? " );

    ps.setInt(1,iddespesa);

    ResultSet rs = ps.executeQuery();

    if (rs.next())
    {
    return true;
    }
    else
    {
    return false;
    }
    }

    catch (SQLException ex)
    {

    ex.printStackTrace();
    return false;
    }
    }
    -------------------------------------------------------------

    DB connection:

    public boolean connect(String username, String password) throws ClassNotFoundException
    {
    try
    {

    String url = "jdbc:mysql://localhost:3306/OrcDataBase";
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url, username,password);

    System.out.println("connected");


    con.setAutoCommit(false);

    return true;
    }
    catch (SQLException ex)
    {
    return false;
    }
    }

    I can make a connection to mysql database, because i can see a process running with th user that i make the connection but when i make the call to the select it generates the error "Exception occurred during event dispatching:java.lang.NullPointerException".

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    When posting code can you please use code tags?

    Also, what line is that exception being thrown from?

  3. #3
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    The exception is been thrown in this line of code:

    ps = con.prepareStatement("SELECT iddespesa FROM despesas where iddespesa = ? " );

    here is the catch to the java.null

    catch (SQLException ex)
    {
    /*ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    fireExceptionGenerated(event);*/
    ex.printStackTrace();

    return false;
    }

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    Quote Originally Posted by oliveira View Post
    The exception is been thrown in this line of code:

    Java Code:
    ps = con.prepareStatement("SELECT iddespesa FROM despesas where iddespesa = ? " );
    here is the catch to the java.null
    Java Code:
    	catch (SQLException ex)
    	{
    	    /*ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);*/
                 ex.printStackTrace();
    
    	    return false;
    	}
    con is null.
    You have no connection.

    And I did ask you to use code tags (see this post).

  5. #5
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    This is the part where i make the connection and this is made on the bbegining of the program where a window pop's up where i put the user/password.

    XML Code:
    public boolean connect(String username, String password) throws ClassNotFoundException
        {
    	try
    	{
                String url = "jdbc:mysql://localhost:3306/OrcDataBase";
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, username,password);
                System.out.println("connected");
    
    	       con.setAutoCommit(false);
    
    	     return true;
    	 }
    	catch (SQLException ex)
    	{
    	    return false;
    	}
     }

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    You create a connection in that method, but do nothing with it.
    It's local to that method, so is never passed out.

  7. #7
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    OK i understand what you're saying, but i had this working with a access database, the select was working, but when i moved to a mysql database this part is not working anymore so i have to check were i'm i loosing the conection....

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    Sorry, but that code there cannot have created a connection that was used outside of that method. Just not possible.

    Where is your connection object (con) defined that is used to prepare the statement?

  9. #9
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    Java Code:
    Variable con
    protected Connection con;
    
    Constructor
    public BranchModel()
        {
    	con = AccessConection.getInstance().getConnection();
        }
    
    method getInstance
    public static AccessConection getInstance()
        {
    	if (_mvb == null)
    	{
    	    _mvb = new AccessConection();
    	}
    
    	return _mvb;
        }
    
    method getConnection
    public Connection getConnection()
        {
    	return con;
        }
    
    This performs the con = AccessConection.getInstance().getConnection();
    Java Code:
    The next part performs the connection with the driver to mysql
    
    public void setConnection(Connection connect)
        {
    	con = connect;
    
    
    public boolean connect(String username, String password) throws ClassNotFoundException
        {
    	try
    	{
                String url = "jdbc:mysql://localhost:3306/OrcDataBase";
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, username,password);
                System.out.println("connected");
    
    	       con.setAutoCommit(false);
    
    	     return true;
    	 }
    	catch (SQLException ex)
    	{
    	    return false;
    	}
     }

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    Sorry, but can you narrow this down.
    Are you connecting to Access or MySQL?

    If it's the latter you're having a problem with then simply give us that code. Anything else is just noise.

    That second section of code (assuming it's what we should be looking at) Does not show the connection object in relation to that prepareStatement() call.

    You have a setConnection(), but don't show us where that connection comes from...which is sort of important since it's the connection that's null!

    So, please, help us help you by providing relevant and sufficient information.

  11. #11
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    ----Class AccessConnection--------

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package monitorizacao;
    
    /**
     *
     * @author Consultor
     */
    // File: MvbOracleConnection.java
    
    import java.sql.*;
    
    
    /*
     * This class is a singleton class that provides methods
     * to connect to an Oracle database, return the connection,
     * set the connection, and determine whether or not the Oracle
     * JDBC driver has been loaded. To obtain a reference to an
     * instance of this class, use the getInstance() method.
     */
    public class AccessConection
    {
        private static AccessConection _mvb = null;
        protected Connection con = null;
        protected boolean driverLoaded = false;
    
    
        /*
         * The constructor is declared protected so that only subclasses
         * can access it.
         */
        protected AccessConection()
        {
    	// empty
        }
    
    
        /*
         * Returns an instance of MvbOracleConnection
         */
        public static AccessConection getInstance()
        {
    	if (_mvb == null)
    	{
    	    _mvb = new AccessConection();
    	}
    
    	return _mvb;
        }
    
    
        /*
         * Loads the Oracle JDBC driver and connects to the database named ug using
         * the given username and password.
         * Returns true if the connection is successful; false otherwise.
         */
        public boolean connect(String username, String password) throws ClassNotFoundException
        {
    	try
    	{
    
    
                String url = "jdbc:mysql://localhost:3306/OrcDataBase";
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, username,password);
    
                System.out.println("connected");
    
    	    con.setAutoCommit(false);
    
    	    return true;
    	}
    	catch (SQLException ex)
    	{
    	    return false;
    	}
        }
    
    
        /*
         * Returns the connection
         */
        public Connection getConnection()
        {
    	return con;
        }
    
    
        /*
         * Sets the connection
         */
        public void setConnection(Connection connect)
        {
    	con = connect;
        }
    
    
        /*
         * Returns true if the driver is loaded; false otherwise
         */
        public boolean isDriverLoaded()
        {
    	return driverLoaded;
        }
    
    
        /*
         * This method allows members of this class to clean up after itself
         * before it is garbage collected. It is called by the garbage collector.
         */
        protected void finalize() throws Throwable
        {
    	if (con != null)
    	{
    	    con.close();
    	}
    
    	// finalize() must call super.finalize() as the last thing it does
    	super.finalize();
        }
    }

    --------class BranchModel---------
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package monitorizacao;
    
    /**
     *
     * @author Consultor
     */
    // File: BranchModel.java
    
    import java.sql.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.event.EventListenerList;
    import monitorizacao.Transaction.InvalidTransferException;
    
    
    /*
     * BranchModel is a database interface class that provides methods to
     * insert a branch, update the name of a branch, delete a branch, return
     * a ResultSet containing all branches, determine the existence of a particular
     * branch, and return the database connection used by this class.
     *
     * Each insert, update, and delete method is treated as a transaction, i.e., they
     * commit the change. If you want to use those methods as helper functions for a
     * larger transaction, you would have to write non commit() versions of those methods,
     * so that you can treat the larger transaction as a single transaction.
     *
     * The database connection in MvbOracleConnection must be set before any database
     * access methods can be used. (This was done when connect() was called by the
     * LoginWindow). This class is defined in MvbOracleConnection.java.
     *
     * BranchModel allows components to register for exception events when
     * an exception occurs in the model.  Exceptions are part of the
     * Java 2 API, but exception events aren't.  We are creating our own
     * event/listener. The BranchController class registers itself as
     * a listener to BranchModel so that it can display the exception
     * messages.  The file ExceptionEvent.java contains the class
     * definition of ExceptionEvent.  The file ExceptionListener.java
     * contains the interface that components must implement in order
     * to receive exception events.
     */
    
    
    public class BranchModel
    {
        protected PreparedStatement ps = null;
        protected EventListenerList listenerList = new EventListenerList();
        protected Connection con;
        Transaction despesa = new Transaction();
        ResultSet rs = null;
    
    
             public class InvalidTransferException extends Exception{
    
            public InvalidTransferException(String message) {
                super(message);
            }
        }
    
        /*
         * Default constructor
         * Precondition: The Connection object in MvbOracleConnection must be
         * a valid database connection.
         */
        public BranchModel()
        {
    	con = AccessConection.getInstance().getConnection();
        }
    
    
    
         public void makeExpense(float transferAmount,int accountNumber,String fromTable) throws SQLException, InvalidTransferException
        {
            Statement stmt = null;
            ResultSet rset = null;
            Connection conn = AccessConection.getInstance().getConnection();
            conn.setAutoCommit(false);
    
            try{
                stmt = conn.createStatement();
                rset = stmt.executeQuery("Select Saldo from " + fromTable + " where idconta = " + accountNumber);
                rset.next();
                float fromBalance = rset.getFloat(1);
                if(fromBalance < transferAmount){
    
                    throw new InvalidTransferException("Saldo insuficiente");
                }
                rset.close();
                rset= stmt.executeQuery("Select Saldo From " + fromTable + " where idconta = " + accountNumber);
                rset.next();
                fromBalance -= transferAmount;
                stmt.executeUpdate("Update " + fromTable + "SET Saldo = " + fromBalance + " where idconta = "+ accountNumber);
                conn.commit();
    
            }
            catch(SQLException sqle){
                conn.rollback();
                throw sqle;
            }
            finally{
               // if(rset != null)rset.close();
               // if(stmt != null)rset.close();
                conn.close();
            }
        }
    
        /*
         * Inserts a tuple into the branch table. The object wrapper for the int datatype
         * is used so that null can be inserted, e.g., to insert null
         * into the branch_phone column, set the bphone argument to null. If a 10 digit phone
         * number is used, change the data type for the phone number from Integer to Long.
         * Returns true if the insert is successful; false otherwise.
         *
         * Only baddr and bphone can be null.
         */
        public boolean insertBranch(Integer iddespesa, int value, Date data, String tipo,
    				       Integer idconta, String owner) throws InvalidTransferException
        {
            
    	try
    	{
    
    	    ps = con.prepareStatement("INSERT INTO Despesas VALUES (?,?,?,?,?)");
    
                ps.setInt(1,iddespesa.intValue());
    
    	    ps.setInt(2,value);
    
    	    if (data != null)
    	    {
    		ps.setDate(3, data);
    	    }
    	    else
    	    {
    		ps.setString(3,null);
    	    }
    
    	    ps.setString(4,tipo);
    
    	    if (idconta != null)
    	    {
    		ps.setInt(5,idconta.intValue());
    	    }
    	    else
    	    {
    		ps.setNull(5,Types.INTEGER);
    	    }
    
                ps.setString(6,owner);
    
                ps.executeUpdate();
                con.commit();
    
                  return true;
    	}
    	catch (SQLException ex)
    	{
    	    ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);
    
    	    try
    	    {
    		con.rollback();
                  //  con.close();
    		return false;
    	    }
    	    catch (SQLException ex2)
    	    {
    		event = new ExceptionEvent(this, ex2.getMessage());
    		fireExceptionGenerated(event);
    		return false;
    	    }
    
    	}
    
    
        }
    
    
        /*
         * Updates the name of a branch
         * Returns true if the update is successful; false otherwise.
         *
         * bname cannot be null.
         */
    
        public boolean updateBranch(int id_despesa, String tipo)
        {
    	try
    	{
    	    ps = con.prepareStatement("UPDATE Despesas SET tipo = ? WHERE iddespesa = ?");
    
    	    if (tipo != null)
    	    {
    		ps.setString(1, tipo);
    	    }
    	    else
    	    {
    		return false;
    	    }
    
    	    ps.setInt(2, id_despesa);
    
    	    ps.executeUpdate();
    
    	    con.commit();
    
    	    return true;
    	}
    	catch (SQLException ex)
    	{
    	    ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);
    
    	    try
    	    {
    		con.rollback();
    		return false;
    	    }
    	    catch (SQLException ex2)
    	    {
    		 event = new ExceptionEvent(this, ex2.getMessage());
    		 fireExceptionGenerated(event);
    		 return false;
    	    }
    	}
        }
    
        public boolean updateBranchtype(String tipo)
        {
    	try
    	{
    	    ps = con.prepareStatement("UPDATE Despesas SET tipo = ? WHERE tipo = ?");
    
    	    if (tipo != null)
    	    {
    		ps.setString(1, tipo);
    	    }
    	    else
    	    {
    		return false;
    	    }
    
    	    //ps.setInt(2, id_despesa);
    
    	    ps.executeUpdate();
    
    	    con.commit();
    
    	    return true;
    	}
    	catch (SQLException ex)
    	{
    	    ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);
    
    	    try
    	    {
    		con.rollback();
    		return false;
    	    }
    	    catch (SQLException ex2)
    	    {
    		 event = new ExceptionEvent(this, ex2.getMessage());
    		 fireExceptionGenerated(event);
    		 return false;
    	    }
    	}
        }
    
    
        /*
         * Deletes a branch.
         * Returns true if the delete is successful; false otherwise.
         */
        public boolean deleteBranch(int iddespesa)
        {
    	try
    	{
    	    ps = con.prepareStatement("DELETE FROM Despesas WHERE iddespesa = ?");
    
    	    ps.setInt(1, iddespesa);
    
    	    ps.executeQuery();
    
    	    con.commit();
    
    	    return true;
    	}
    	catch (SQLException ex)
    	{
    	    ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);
    
    	    try
    	    {
    		con.rollback();
    		return false;
    	    }
    	    catch (SQLException ex2)
    	    {
    		event = new ExceptionEvent(this, ex2.getMessage());
    		fireExceptionGenerated(event);
    		return false;
    	    }
    	}
        }
    
    
        /*
         * Returns a ResultSet containing all branches. The ResultSet is
         * scroll insensitive and read only. If there is an error, null
         * is returned.
         */
        public ResultSet showBranch()
        {
    	try
    	{
    	    ps = con.prepareStatement("SELECT b.* FROM Despesas b",
    				      ResultSet.TYPE_SCROLL_INSENSITIVE,
    				      ResultSet.CONCUR_READ_ONLY);
    
    	    ResultSet rs = ps.executeQuery();
    
    	    return rs;
    	}
    	catch (SQLException ex)
    	{
    	    ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);
    	    // no need to commit or rollback since it is only a query
    
    	    return null;
    	}
        }
    
    
        /*
         * Same as showBranch() except that an updatable result set
         * is returned.
         */
        public ResultSet editBranch()
        {
    	try
    	{
    	    ps = con.prepareStatement("SELECT b.* FROM Despesas b",
    				      ResultSet.TYPE_SCROLL_INSENSITIVE,
    				      ResultSet.CONCUR_UPDATABLE);
    
    	    ResultSet rs = ps.executeQuery();
    
    	    return rs;
    	}
    	catch (SQLException ex)
    	{
    	    ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);
    	    // no need to commit or rollback since it is only a query
    
    	    return null;
    	}
        }
    
    
        /*
         * Returns true if the branch exists; false
         * otherwise.
         */
        public boolean findBranch(Integer iddespesa)
        {
       
    	try
    	{
    
               con = AccessConection.getInstance().getConnection();
    	       ps = con.prepareStatement("SELECT iddespesa FROM despesas where iddespesa = ? " );
    
    
               ps.setInt(1,iddespesa);
    
    	    ResultSet rs = ps.executeQuery();
    
    	    if (rs.next())
    	    {
    		return true;
    	    }
    	    else
    	    {
    		return false;
    	    }
    	}
    
    	catch (SQLException ex)
    	{
    
                 ex.printStackTrace();
    
    	    return false;
    	}
        }
    
    
        /*
         * Returns the database connection used by this branch model
         */
        public Connection getConnection()
        {
    	return con;
        }
    
    
        /*
         * This method allows members of this class to clean up after itself
         * before it is garbage collected. It is called by the garbage collector.
         */
        protected void finalize() throws Throwable
        {
    	if (ps != null)
    	{
    	    ps.close();
    	}
    
    	// finalize() must call super.finalize() as the last thing it does
    	super.finalize();
        }
    
    
        /******************************************************************************
         * Below are the methods to add and remove ExceptionListeners.
         *
         * Whenever an exception occurs in BranchModel, an exception event
         * is sent to all registered ExceptionListeners.
         ******************************************************************************/
    
        public void addExceptionListener(ExceptionListener l)
        {
    	listenerList.add(ExceptionListener.class, l);
        }
    
    
        public void removeExceptionListener(ExceptionListener l)
        {
    	listenerList.remove(ExceptionListener.class, l);
        }
    
    
        /*
         * This method notifies all registered ExceptionListeners.
         * The code below is similar to the example in the Java 2 API
         * documentation for the EventListenerList class.
         */
        public void fireExceptionGenerated(ExceptionEvent ex)
        {
    	// Guaranteed to return a non-null array
    	Object[] listeners = listenerList.getListenerList();
    
    	// Process the listeners last to first, notifying
    	// those that are interested in this event.
    	// I have no idea why the for loop counts backwards by 2
    	// and the array indices are the way they are.
    	for (int i = listeners.length-2; i>=0; i-=2)
    	{
    	    if (listeners[i]==ExceptionListener.class)
    	    {
    		((ExceptionListener)listeners[i+1]).exceptionGenerated(ex);
    	    }
             }
         }
    }
    ------class LoginWindow ----------
    Java Code:
    // File: LoginWindow.java
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    
    /*
     * The login window
     */ 
    public class LoginWindow extends JDialog implements ActionListener
    {
        // MvbOracleConnection represents a connection to an Oracle database
        private MvbOracleConnection mvb = MvbOracleConnection.getInstance();
    
        // user is allowed 3 login attempts
        private int loginAttempts = 0;
        
        // components of the login window
        private JTextField usernameField = new JTextField(10);
        private JPasswordField passwordField = new JPasswordField(10);	   
        private JLabel usernameLabel = new JLabel("Enter username:  ");
        private JLabel passwordLabel = new JLabel("Enter password:  ");
        private JButton loginButton = new JButton("Log In");
    
    
        /*
         * Default constructor. The login window is constructed here.
         */
        public LoginWindow(JFrame parent)
        {
    	super(parent, "User Login", true);
    	setResizable(false);
    	
    	passwordField.setEchoChar('*');
    	
    	// content pane for the login window
    	JPanel loginPane = new JPanel();
    	setContentPane(loginPane);
    
    
    	/*
    	 * layout components using the GridBag layout manager
    	 */ 
    	
    	GridBagLayout gb = new GridBagLayout();
    	GridBagConstraints c = new GridBagConstraints();
    	
    	loginPane.setLayout(gb);
    	loginPane.setBorder(BorderFactory.createEmptyBorder(12, 12, 11, 11));
    	
    	// place the username label 
    	c.gridwidth = GridBagConstraints.RELATIVE;
    	c.insets = new Insets(10, 10, 5, 0);
    	gb.setConstraints(usernameLabel, c);
    	loginPane.add(usernameLabel);
    	
    	// place the text field for the username 
    	c.gridwidth = GridBagConstraints.REMAINDER;
    	c.insets = new Insets(10, 0, 5, 10);
    	gb.setConstraints(usernameField, c);
    	loginPane.add(usernameField);
    	
    	// place password label
    	c.gridwidth = GridBagConstraints.RELATIVE;
    	c.insets = new Insets(0, 10, 10, 0);
    	gb.setConstraints(passwordLabel, c);
    	loginPane.add(passwordLabel);
    	
    	// place the password field 
    	c.gridwidth = GridBagConstraints.REMAINDER;
    	c.insets = new Insets(0, 0, 10, 10);
    	gb.setConstraints(passwordField, c);
    	loginPane.add(passwordField);
    	    
    	// place the login button
    	c.gridwidth = GridBagConstraints.REMAINDER;
    	c.insets = new Insets(10, 10, 5, 10);
    	c.anchor = GridBagConstraints.CENTER;
    	gb.setConstraints(loginButton, c);
    	loginPane.add(loginButton);
    	
    	// end of layout
    	
    	// Register password field and OK button with action event handler.
    	// An action event is generated when the return key is pressed while 
    	// the cursor is in the password field or when the OK button is pressed.
    	passwordField.addActionListener(this);
    	loginButton.addActionListener(this);
    	    
    	// anonymous inner class for closing the window
    	addWindowListener(new WindowAdapter() 
    	{
    	    public void windowClosing(WindowEvent e) 
    	    { 
    		System.exit(0); 
    	    }
    	 });
    
    	// initially, place the cursor in the username text field
    	usernameField.requestFocus();	  
    	}
    
           
        /*
         * event handler for password field and OK button
         */ 	    
        public void actionPerformed(ActionEvent e) 
        {
    	if (mvb.connect(usernameField.getText(), 
    			     String.valueOf(passwordField.getPassword())))
    	{
    	    // if the username and password are valid, 
    	    // get rid of the login window
    	    dispose();     
    	}
    	else
    	{
    	    loginAttempts++;
    		
    	    if (loginAttempts >= 3)
    	    {
    		dispose();
    		System.exit(0);
    	    }
    	    else
    	    {
    		// clear the password
    		passwordField.setText("");
    	    }
    	}  
        }     
    }

    ---------class BranchController--------
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package monitorizacao;
    
    /**
     *
     * @author Consultor
     */
    // File: BranchController.java
    
    import java.awt.*;
    import java.awt.event.*;
    import java.text.ParseException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.sql.*;
    import java.text.SimpleDateFormat;
    import monitorizacao.Transaction.InvalidTransferException;
    
    
    
    /*
     * BranchController is a control class that handles action events
     * on the Branch Admin menu. It also updates the GUI based on
     * which menu item the user selected. This class contains the following
     * inner classes: BranchInsertDialog, BranchUpdateDialog, and
     * BranchDeleteDialog. BranchInsertDialog is a dialog box that allows a
     * user to insert a branch. BranchUpdateDialog is a dialog box that allows
     * a user to update the name of a branch. BranchDeleteDialog is a dialog box
     * that allows a user to delete a branch.
     *
     * BranchController implements the ExceptionListener interface which
     * allows it to be notified of any Exceptions that occur in BranchModel
     * (BranchModel contains the database transaction functions). It is defined
     * in BranchModel.java. The ExceptionListener interface is defined in
     * ExceptionListener.java. When an Exception occurs in BranchModel,
     * BranchController will update the status text area of MvbView.
     */
    public class BranchController implements ActionListener, ExceptionListener
    {
        private MvbView mvb = null;
        private BranchModel Despesas = null;
        Transaction transfer = new Transaction();
    
        // constants used for describing the outcome of an operation
        public static final int OPERATIONSUCCESS = 0;
        public static final int OPERATIONFAILED = 1;
        public static final int VALIDATIONERROR = 2;
    
        public BranchController(MvbView mvb)
        {
    	this.mvb = mvb;
    	Despesas = new BranchModel();
    
    	// register to receive exception events from branch
    	Despesas.addExceptionListener(this);
        }
    
    
        /*
         * This event handler gets called when the user makes a menu
         * item selection.
         */
        public void actionPerformed(ActionEvent e)
        {
    	String actionCommand = e.getActionCommand();
    
    	// you cannot use == for string comparisons
    	if (actionCommand.equals("Inserir despesa"))
    	{
    	    BranchInsertDialog iDialog = new BranchInsertDialog(mvb);
    	    iDialog.pack();
    	    mvb.centerWindow(iDialog);
    	    iDialog.setVisible(true);
    	    return;
    	}
    
    	if (actionCommand.equals("Actualizar despesa"))
    	{
    	    BranchUpdateDialog uDialog = new BranchUpdateDialog(mvb);
    	    uDialog.pack();
    	    mvb.centerWindow(uDialog);
    	    uDialog.setVisible(true);
    	    return;
    	}
    
    	if (actionCommand.equals("Apagar despesa"))
    	{
    	    BranchDeleteDialog dDialog = new BranchDeleteDialog(mvb);
    	    dDialog.pack();
    	    mvb.centerWindow(dDialog);
    	    dDialog.setVisible(true);
    	    return;
    	}
    
    	if (actionCommand.equals("Mostrar despesas"))
    	{
    	    showAllBranches();
    	    return;
    	}
    
    	if (actionCommand.equals("Editar despesas"))
    	{
    	    editAllBranches();
    	    return;
    	}
        }
    
    
        /*
         * This event handler gets called when an exception event
         * is generated. It displays the exception message on the status
         * text area of the main GUI.
         */
        public void exceptionGenerated(ExceptionEvent ex)
        {
    	String message = ex.getMessage();
    
    	// annoying beep sound
    	Toolkit.getDefaultToolkit().beep();
    
    	if (message != null)
    	{
    	    mvb.updateStatusBar(ex.getMessage());
    	}
    	else
    	{
    	    mvb.updateStatusBar("An exception occurred!");
    	}
        }
    
    
        /*
         * This method displays all branches in a non-editable JTable
         */
        private void showAllBranches()
        {
    	ResultSet rs = Despesas.showBranch();
    
    	// CustomTableModel maintains the result set's data, e.g., if
    	// the result set is updatable, it will update the database
    	// when the table's data is modified.
    	CustomTableModel model = new CustomTableModel(Despesas.getConnection(), rs);
    	CustomTable data = new CustomTable(model);
    
    	// register to be notified of any exceptions that occur in the model and table
    	model.addExceptionListener(this);
    	data.addExceptionListener(this);
    
    	// Adds the table to the scrollpane.
    	// By default, a JTable does not have scroll bars.
    	mvb.addTable(data);
        }
    
    
        /*
         * This method displays all branches in an editable JTable
         */
        private void editAllBranches()
        {
    	ResultSet rs = Despesas.editBranch();
    
    	CustomTableModel model = new CustomTableModel(Despesas.getConnection(), rs);
    	CustomTable data = new CustomTable(model);
    
    	model.addExceptionListener(this);
    	data.addExceptionListener(this);
    
    	mvb.addTable(data);
        }
    
    
        /*
         * This class creates a dialog box for inserting a branch.
         */
        class BranchInsertDialog extends JDialog implements ActionListener
        {
    	private JTextField ID_expense = new JTextField(4);
    	private JTextField expenseType = new JTextField(10);
    	private JTextField expenseOwner = new JTextField(15);
    	private JTextField expenseValue = new JTextField(10);
    	private JTextField expenseDate = new JTextField(10);
            private JTextField ID_Conta = new JTextField(10);
    
    	/*
    	 * Constructor. Creates the dialog's GUI.
    	 */
    	public BranchInsertDialog(JFrame parent)
    	{
    	    super(parent, "Inserir Despesa", true);
    	    setResizable(false);
    
    	    JPanel contentPane = new JPanel(new BorderLayout());
    	    setContentPane(contentPane);
    	    contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    
    	    // this panel will contain the text field labels and the text fields.
    	    JPanel inputPane = new JPanel();
    	    inputPane.setBorder(BorderFactory.createCompoundBorder(
    			 new TitledBorder(new EtchedBorder(), "Despesas"),
    			 new EmptyBorder(5, 5, 5, 5)));
    
    	    // add the text field labels and text fields to inputPane
    	    // using the GridBag layout manager
    
    	    GridBagLayout gb = new GridBagLayout();
    	    GridBagConstraints c = new GridBagConstraints();
    	    inputPane.setLayout(gb);
    
    	    // create and place branch id label
    	    JLabel label= new JLabel("ID Despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(0, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch id field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(0, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(ID_expense, c);
    	    inputPane.add(ID_expense);
    
    	    // create and place branch name label
    	    label = new JLabel("Tipo Despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(5, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch name field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(expenseType, c);
    	    inputPane.add(expenseType);
    
    	    // create and place branch address label
    	    label = new JLabel("Despesa efectuada por: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(5, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch address field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(expenseOwner, c);
    	    inputPane.add(expenseOwner);
    
    	    // create and place branch city label
    	    label = new JLabel("Valor da Despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(5, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch city field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(expenseValue, c);
    	    inputPane.add(expenseValue);
    
                // create and place branch conta label
    	    label = new JLabel("ID Conta: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(5, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch city field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(ID_Conta, c);
    	    inputPane.add(ID_Conta);
    
    	    // create and place branch phone label
    	    label = new JLabel("Data despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(5, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch phone field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(expenseDate, c);
    	    inputPane.add(expenseDate);
    
    	    // when the return key is pressed in the last field
    	    // of this form, the action performed by the ok button
    	    // is executed
    	    expenseDate.addActionListener(this);
    	    expenseDate.setActionCommand("OK");
    
    	    // panel for the OK and cancel buttons
    	    JPanel buttonPane = new JPanel();
    	    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
    	    buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));
    
    	    JButton OKButton = new JButton("OK");
    	    JButton cancelButton = new JButton("Cancel");
    	    OKButton.addActionListener(this);
    	    OKButton.setActionCommand("OK");
    	    cancelButton.addActionListener(new ActionListener()
    		{
    		    public void actionPerformed(ActionEvent e)
    		    {
    			dispose();
    		    }
    		});
    
    	    // add the buttons to buttonPane
    	    buttonPane.add(Box.createHorizontalGlue());
    	    buttonPane.add(OKButton);
    	    buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
    	    buttonPane.add(cancelButton);
    
    	    contentPane.add(inputPane, BorderLayout.CENTER);
    	    contentPane.add(buttonPane, BorderLayout.SOUTH);
    
    	    addWindowListener(new WindowAdapter()
    		{
    		    public void windowClosing(WindowEvent e)
    		    {
    			dispose();
    		    }
    		});
    	}
    
    
    	/*
    	 * Event handler for the OK button in BranchInsertDialog
    	 */
    	public void actionPerformed(ActionEvent e)
    	{
    	    String actionCommand = e.getActionCommand();
    
    	    if (actionCommand.equals("OK"))
    	    {
                    try {
                        if (validateInsert() != VALIDATIONERROR) {
                            dispose();
                        } else {
                            Toolkit.getDefaultToolkit().beep();
                            // display a popup to inform the user of the validation error
                            JOptionPane errorPopup = new JOptionPane();
                            errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (BranchModel.InvalidTransferException ex) {
                        Logger.getLogger(BranchController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                   }
    	}
    
    
    	/*
    	 * Validates the text fields in BranchInsertDialog and then
    	 * calls branch.insertBranch() if the fields are valid.
    	 * Returns the operation status, which is one of OPERATIONSUCCESS,
    	 * OPERATIONFAILED, VALIDATIONERROR.
    	 */
    	private int validateInsert() throws BranchModel.InvalidTransferException {
    
    
    	    try
    	    {
    		Integer iddespesa;
    		int value;
    		Date data;
    		String tipo;
    		Integer idconta;
                    String owner;
    
    
    		if (ID_expense.getText().trim().length() != 0)
    		{
    		    iddespesa = Integer.valueOf(ID_expense.getText().trim());
    
    		    // check for duplicates
    		    if (Despesas.findBranch(iddespesa))
    		    {
    			Toolkit.getDefaultToolkit().beep();
    			mvb.updateStatusBar("Despesas " + iddespesa + " already exists!");
    			return OPERATIONFAILED;
    		    }
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		if (expenseType.getText().trim().length() != 0)
    		{
    		    tipo = expenseType.getText().trim();
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		if (expenseOwner.getText().trim().length() != 0)
    		{
    		    owner = expenseOwner.getText().trim();
    		}
    		else
    		{
    		    owner = null;
    		}
    
    		if (expenseValue.getText().trim().length() != 0)
    		{
    		    value = Integer.valueOf(expenseValue.getText().trim());
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		if (expenseDate.getText().trim().length() != 0)
    		{
    
                        data = Date.valueOf(expenseDate.getText().trim());
    
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
                    if (ID_Conta.getText().trim().length() != 0)
    		{
    		    idconta = Integer.valueOf(ID_Conta.getText().trim());
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		mvb.updateStatusBar("Inserindo despesa...");
    
                   
    		if (Despesas.insertBranch(iddespesa,value,data,tipo,idconta,owner))
    		{
    		    mvb.updateStatusBar("Sucesso.");
    		    showAllBranches();                    
    		    return OPERATIONSUCCESS;
    		}
    		else
    		{
    		    Toolkit.getDefaultToolkit().beep();
    		    mvb.updateStatusBar("Falha...");
    		    return OPERATIONFAILED;
    		}
                    }
    	    
    	    catch (NumberFormatException ex)
    	    {
    		// this exception is thrown when a string
    		// cannot be converted to a number
    		return VALIDATIONERROR;
    	    }
    	}
        }
    
    
        /*
         * This class creates a dialog box for updating a branch.
         */
        class BranchUpdateDialog extends JDialog implements ActionListener
        {
    	private JTextField ID_expense = new JTextField(4);
    	private JTextField expenseType = new JTextField(10);
            private JTextField expenseType1 = new JTextField(10);
    
    	/*
    	 * Constructor. Creates the dialog's GUI.
    	 */
    	public BranchUpdateDialog(JFrame parent)
    	{
    	    super(parent, "Actualizar Despesa", true);
    	    setResizable(false);
    
    	    JPanel contentPane = new JPanel(new BorderLayout());
    	    setContentPane(contentPane);
    	    contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    
    	    // this panel contains the text field labels and
    	    // the text fields.
    	    JPanel inputPane = new JPanel();
    	    inputPane.setBorder(BorderFactory.createCompoundBorder(
    			 new TitledBorder(new EtchedBorder(), "Despesas"),
    			 new EmptyBorder(5, 5, 5, 5)));
    
    	    // add the text field labels and text fields to inputPane
    	    // using the GridBag layout manager
    
    	    GridBagLayout gb = new GridBagLayout();
    	    GridBagConstraints c = new GridBagConstraints();
    	    inputPane.setLayout(gb);
    
      	    // create and place branch id label
    	    JLabel label= new JLabel("ID Despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(0, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch id field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(0, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(ID_expense, c);
    	    inputPane.add(ID_expense);
    
                // create and place branch name label
    	    label = new JLabel("Alterar todos tipos despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch name field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(expenseType1, c);
    	    inputPane.add(expenseType1);
    
    	    // create and place branch name label
    	    label = new JLabel("Actualizar tipo despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(5, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch name field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(5, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(expenseType, c);
    	    inputPane.add(expenseType);
    
    	    // when the return key is pressed in the last field
    	    // of this form, the action performed by the ok button
    	    // is executed
    	    expenseType.addActionListener(this);
    	    expenseType.setActionCommand("OK");
    
    	    // panel for the OK and cancel buttons
    	    JPanel buttonPane = new JPanel();
    	    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
    	    buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));
    
    	    JButton OKButton = new JButton("OK");
    	    JButton cancelButton = new JButton("Cancel");
    	    OKButton.addActionListener(this);
    	    OKButton.setActionCommand("OK");
    	    cancelButton.addActionListener(new ActionListener()
    		{
    		    public void actionPerformed(ActionEvent e)
    		    {
    			dispose();
    		    }
    		});
    
    	    // add buttons to buttonPane
    	    buttonPane.add(Box.createHorizontalGlue());
    	    buttonPane.add(OKButton);
    	    buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
    	    buttonPane.add(cancelButton);
    
    	    contentPane.add(inputPane, BorderLayout.CENTER);
    	    contentPane.add(buttonPane, BorderLayout.SOUTH);
    
    	    addWindowListener(new WindowAdapter()
    		{
    		    public void windowClosing(WindowEvent e)
    		    {
    			dispose();
    		    }
    		});
    	}
    
    
    	/*
    	 * Event handler for the OK button in BranchUpdateDialog
    	 */
    	public void actionPerformed(ActionEvent e)
    	{
    	    String actionCommand = e.getActionCommand();
    
    	    if (actionCommand.equals("OK"))
    	    {
    		if (validateUpdate() != VALIDATIONERROR)
    		{
    		    dispose();
    		}
                    if (validateUpdateExpenseType() != VALIDATIONERROR)
    		{
    		    dispose();
    		}
                    else
    		{
    		    Toolkit.getDefaultToolkit().beep();
    
    		    // display a popup to inform the user of the error
    		    JOptionPane errorPopup = new JOptionPane();
    		    errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
    		}
    	    }
    	}
    
    
    	/*
    	 * Validates the text fields in BranchUpdateDialog and then
    	 * calls branch.branchUpdate() if the fields are valid.
    	 * Returns the operation status.
    	 */
    	private int validateUpdate()
    	{
    	    try
    	    {
    		int iddespesa;
    		String tipo;
    
    		if (ID_expense.getText().trim().length() != 0)
    		{
    		    iddespesa = Integer.valueOf(ID_expense.getText().trim()).intValue();
    
    		    // check if branch exists
    		    if (!Despesas.findBranch(iddespesa))
    		    {
    			Toolkit.getDefaultToolkit().beep();
    			mvb.updateStatusBar("Branch " + iddespesa + " does not exist!");
    			return OPERATIONFAILED;
    		    }
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		if (expenseType.getText().trim().length() != 0)
    		{
    		    tipo = expenseType.getText().trim();
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		mvb.updateStatusBar("Updating branch...");
    
    		if (Despesas.updateBranch(iddespesa, tipo))
    		{
    		    mvb.updateStatusBar("Operation successful.");
    		    showAllBranches();
    		    return OPERATIONSUCCESS;
    		}
    		else
    		{
    		    Toolkit.getDefaultToolkit().beep();
    		    mvb.updateStatusBar("Operation failed.");
    		    return OPERATIONFAILED;
    		}
    	    }
    	    catch (NumberFormatException ex)
    	    {
    		return VALIDATIONERROR;
    	    }
    	}
    
    
        private int validateUpdateExpenseType()
    	{
    	    try
    	    {
    		String tipo;
    
    
    		if (expenseType1.getText().trim().length() != 0)
    		{
    		    tipo = expenseType1.getText().trim();
    
    		    // check if branch exists
    		    if (!Despesas.updateBranchtype(tipo))
    		    {
    			Toolkit.getDefaultToolkit().beep();
    			mvb.updateStatusBar("Despesa " + tipo + " nao existe!");
    			return OPERATIONFAILED;
    		    }
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		if (expenseType.getText().trim().length() != 0)
    		{
    		    tipo = expenseType.getText().trim();
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		mvb.updateStatusBar("Updating branch...");
    
    		if (Despesas.updateBranchtype(tipo))
    		{
    		    mvb.updateStatusBar("Operation successful.");
    		    showAllBranches();
    		    return OPERATIONSUCCESS;
    		}
    		else
    		{
    		    Toolkit.getDefaultToolkit().beep();
    		    mvb.updateStatusBar("Operation failed.");
    		    return OPERATIONFAILED;
    		}
    	    }
    	    catch (NumberFormatException ex)
    	    {
    		return VALIDATIONERROR;
    	    }
            }}
    
        /*
         * This class creates a dialog box for deleting a branch.
         */
        class BranchDeleteDialog extends JDialog implements ActionListener
        {
    	private JTextField ID_expense = new JTextField(4);
    
    
    	/*
    	 * Constructor. Creates the dialog's GUI.
    	 */
    	public BranchDeleteDialog(JFrame parent)
    	{
    	    super(parent, "Apagar Despesa", true);
    	    setResizable(false);
    
    	    JPanel contentPane = new JPanel(new BorderLayout());
    	    setContentPane(contentPane);
    	    contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    
    	    // this panel contains the text field labels and the text fields.
    	    JPanel inputPane = new JPanel();
    	    inputPane.setBorder(BorderFactory.createCompoundBorder(
    			 new TitledBorder(new EtchedBorder(), "Branch Fields"),
    			 new EmptyBorder(5, 5, 5, 5)));
    
    	    // add the text field labels and text fields to inputPane
    	    // using the GridBag layout manager
    
    	    GridBagLayout gb = new GridBagLayout();
    	    GridBagConstraints c = new GridBagConstraints();
    	    inputPane.setLayout(gb);
    
    	    // create and place branch id label
    	    JLabel label= new JLabel("ID Despesa: ", SwingConstants.RIGHT);
    	    c.gridwidth = GridBagConstraints.RELATIVE;
    	    c.insets = new Insets(0, 0, 0, 5);
    	    c.anchor = GridBagConstraints.EAST;
    	    gb.setConstraints(label, c);
    	    inputPane.add(label);
    
    	    // place branch id field
    	    c.gridwidth = GridBagConstraints.REMAINDER;
    	    c.insets = new Insets(0, 0, 0, 0);
    	    c.anchor = GridBagConstraints.WEST;
    	    gb.setConstraints(ID_expense, c);
    	    inputPane.add(ID_expense);
    
    	    // when the return key is pressed while in the
    	    // branchID field, the action performed by the ok button
    	    // is executed
    	    ID_expense.addActionListener(this);
    	    ID_expense.setActionCommand("OK");
    
    	    // panel for the OK and cancel buttons
    	    JPanel buttonPane = new JPanel();
    	    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
    	    buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));
    
    	    JButton OKButton = new JButton("OK");
    	    JButton cancelButton = new JButton("Cancel");
    	    OKButton.addActionListener(this);
    	    OKButton.setActionCommand("OK");
    	    cancelButton.addActionListener(new ActionListener()
    		{
    		    public void actionPerformed(ActionEvent e)
    		    {
    			dispose();
    		    }
    		});
    
    	    // add buttons to buttonPane
    	    buttonPane.add(Box.createHorizontalGlue());
    	    buttonPane.add(OKButton);
    	    buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
    	    buttonPane.add(cancelButton);
    
    	    contentPane.add(inputPane, BorderLayout.CENTER);
    	    contentPane.add(buttonPane, BorderLayout.SOUTH);
    
    	    addWindowListener(new WindowAdapter()
    		{
    		    public void windowClosing(WindowEvent e)
    		    {
    			dispose();
    		    }
    		});
    	}
    
    
    	/*
    	 * Event handler for the OK button in BranchDeleteDialog
    	 */
    	public void actionPerformed(ActionEvent e)
    	{
    	    String actionCommand = e.getActionCommand();
    
    	    if (actionCommand.equals("OK"))
    	    {
    		if (validateDelete() != VALIDATIONERROR)
    		{
    		    dispose();
    		}
    		else
    		{
    		    Toolkit.getDefaultToolkit().beep();
    
    		    // display a popup to inform the user of the error
    		    JOptionPane errorPopup = new JOptionPane();
    		    errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
    		}
    	    }
    	}
    
    
    	/*
    	 * Validates the text fields in BranchDeleteDialog and then
    	 * calls branch.branchDelete() if the fields are valid.
    	 * Returns the operation status.
    	 */
    	private int validateDelete()
    	{
    	    try
    	    {
    		int iddespesa;
    
    		if (ID_expense.getText().trim().length() != 0)
    		{
    		    iddespesa = Integer.valueOf(ID_expense.getText().trim()).intValue();
    
    		    // check if branch exists
    		    if (!Despesas.findBranch(iddespesa))
    		    {
    			Toolkit.getDefaultToolkit().beep();
    			mvb.updateStatusBar("Branch " + iddespesa + " does not exist!");
    			return OPERATIONFAILED;
    		    }
    		}
    		else
    		{
    		    return VALIDATIONERROR;
    		}
    
    		mvb.updateStatusBar("Deleting branch...");
    
    		if (Despesas.deleteBranch(iddespesa))
    		{
    		    mvb.updateStatusBar("Operation successful.");
    		    showAllBranches();
    		    return OPERATIONSUCCESS;
    		}
    		else
    		{
    		    Toolkit.getDefaultToolkit().beep();
    		    mvb.updateStatusBar("Operation failed.");
    		    return OPERATIONFAILED;
    		}
    	    }
    	    catch (NumberFormatException ex)
    	    {
    		return VALIDATIONERROR;
    	    }
    	}
            }
        }
    This is most of the code for access the mysql database...
    Hope it helps....thank you very much for your concern:)

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    So, please, help us help you by providing relevant and sufficient information.

    Sorry, I can't read that lot...far too much.

    You know the problem, so you'll have to narrow it down.

  13. #13
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    I'm really sorry...
    So begining again this is my class for the connection

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package monitorizacao;
    
    /**
     *
     * @author Consultor
     */
    // File: MvbOracleConnection.java
    
    import java.sql.*;
    
    
    /*
     * This class is a singleton class that provides methods
     * to connect to an Oracle database, return the connection,
     * set the connection, and determine whether or not the Oracle
     * JDBC driver has been loaded. To obtain a reference to an
     * instance of this class, use the getInstance() method.
     */
    public class AccessConection
    {
        private static AccessConection _mvb = null;
        protected Connection con = null;
        protected boolean driverLoaded = false;
    
    
        /*
         * The constructor is declared protected so that only subclasses
         * can access it.
         */
        protected AccessConection()
        {
    	// empty
        }
    
    
        /*
         * Returns an instance of MvbOracleConnection
         */
        public static AccessConection getInstance()
        {
    	if (_mvb == null)
    	{
    	    _mvb = new AccessConection();
    	}
    
    	return _mvb;
        }
    
    
        /*
         * Loads the Oracle JDBC driver and connects to the database named ug using
         * the given username and password.
         * Returns true if the connection is successful; false otherwise.
         */
        public boolean connect(String username, String password) throws ClassNotFoundException
        {
    	try
    	{
    
                //String driver = "com.mysql.jdbc.Driver";
                String url = "jdbc:mysql://localhost:3306/OrcDataBase";
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, username,password);
    	    // change the url if the branch table is located somewhere else
    	    //String url = "jdbc:odbc:OrcDataBase";
                System.out.println("connected");
    
    	    //if (!driverLoaded)
    	    //{
    		//DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
    		//driverLoaded = true;
    	    //}
    
    	    //con = DriverManager.getConnection(url, username, password);
    
    	    con.setAutoCommit(false);
    
    	    return true;
    	}
    	catch (SQLException ex)
    	{
    	    return false;
    	}
        }
    
    
        /*
         * Returns the connection
         */
        public Connection getConnection()
        {
    	return con;
        }
    
    
        /*
         * Sets the connection
         */
        public void setConnection(Connection connect)
        {
    	con = connect;
        }
    
    
        /*
         * Returns true if the driver is loaded; false otherwise
         */
        public boolean isDriverLoaded()
        {
    	return driverLoaded;
        }
    
    
        /*
         * This method allows members of this class to clean up after itself
         * before it is garbage collected. It is called by the garbage collector.
         */
        protected void finalize() throws Throwable
        {
    	if (con != null)
    	{
    	    con.close();
    	}
    
    	// finalize() must call super.finalize() as the last thing it does
    	super.finalize();
        }
    }
    Then i start the constructor for BranchModel where i call the connection with the statement:
    Java Code:
        public BranchModel()
        {
    	con = AccessConection.getInstance().getConnection();
        }
    
     public boolean findBranch(Integer iddespesa)
        {
       
    	try
    	{
    
               con = AccessConection.getInstance().getConnection();
    	   ps = con.prepareStatement("SELECT iddespesa FROM despesas where iddespesa = ? " );
    
                //rs = ps.executeQuery("select iddespesa from Despesas where iddespesa = ? ");
    
               ps.setInt(1,iddespesa);
    
    	    ResultSet rs = ps.executeQuery();
    
    	    if (rs.next())
    	    {
    		return true;
    	    }
    	    else
    	    {
    		return false;
    	    }
    	}
    
    	catch (SQLException ex)
    	{
    	    /*ExceptionEvent event = new ExceptionEvent(this, ex.getMessage());
    	    fireExceptionGenerated(event);*/
                 ex.printStackTrace();
    
    	    return false;
    	}
        }

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    Right.
    Java Code:
        protected Connection con = null;
    You have this connection here in your AccessConnection class.

    However the only time you open a connection is in the connect() method:
    Java Code:
                Connection con = DriverManager.getConnection(url, username,password);
    That connection object there is not the same as the connection object in your AccessConnection instance. It is purely local to the method. The connection you attempt to use, the one returned by getConnection(), is always null.

    That is your problem.

  15. #15
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    Ok i think i'm beggining to understand the problem...ill try something different and then ill post here what was the result.

    Thank you very much for your dedication and attention.
    Superb:)

  16. #16
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    I made a temporary change:

    Java Code:
    Class.forName("com.mysql.jdbc.Driver").newInstance();
                           con = DriverManager.getConnection("jdbc:mysql://localhost:3306/OrcDataBase","","");
                           ps = con.prepareStatement("SELECT iddespesa FROM despesas where iddespesa = ? " );
                           ps.setInt(1,iddespesa);
    and it worked just like you said.......
    Thank you very much once again, but this was working trough a access database, but when i changed to a mysql database, stoped working...
    Last edited by oliveira; 04-13-2011 at 05:45 PM.

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,123
    Rep Power
    20

    Default

    You must have changed something else, because there is no way that was working.

    I suspect this (in connect()):
    Java Code:
    Connection con = DriverManager.getConnection(url, username,password);
    originally said this:
    Java Code:
    con = DriverManager.getConnection(url, username,password);

  18. #18
    oliveira is offline Member
    Join Date
    Dec 2010
    Posts
    15
    Rep Power
    0

    Default

    Well that's all i changed, nothing else and it worked, now is inserting data to the database....:confused:

Similar Threads

  1. Replies: 1
    Last Post: 12-13-2010, 04:19 PM
  2. Replies: 3
    Last Post: 04-30-2010, 08:44 PM
  3. Replies: 5
    Last Post: 08-26-2009, 12:37 PM
  4. Replies: 1
    Last Post: 07-16-2007, 07:32 AM
  5. Replies: 2
    Last Post: 07-04-2007, 06:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •