Results 1 to 10 of 10
  1. #1
    jocdrew21 is offline Senior Member
    Join Date
    Jan 2014
    Posts
    137
    Rep Power
    0

    Default getting values from one class to another without passing into it

    I have been at this program for a while. Here is the issue, I am trying to get the username and password for one class and send them to another. However I cannot send them in the constructor because a database class is getting them and I need that constructor blank. However if I do not pass the class in the constructor I get a NULL error, even better when I do pass it in I seem to get a thread lock. I do try to do my own housekeeping and close the one frame before I open a new one but it doesn't work. I will do my best to show the design of the program.

    program starts
    Java Code:
    public static void main(String[] args) {
    
    		SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				// connects to database and generates a GUI
    				new UserPromptScreen();
    				
    				
    			}
    		});
    
    	}
    the gatekeeper login screen to displayed and the actionListener waits for the button to be pressed
    Java Code:
    public UserPromptScreen() {
    		//shows prompt screen
    		displayScreen();
    		//action listener for JButton
    		listener();
    	}
    Once the button is pressed the JTextFields are set via getters and setters. Then it attempts to create a new instance of a database:

    Java Code:
    void vaildate() {
    		
    		setuserName(userText.getText());
    		setPassWord(passwordText.getText());
    			
    		new DataBaseConnection();
    		
    	}
    	
    	private void listener(){
    		btn.addActionListener(new ActionListener(){
    
    			
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				System.out.println("Inside action");
    				if (e.getSource() == btn) {
    					vaildate();
    				}
    				
    			}
    			
    		});
    	}
    Database constructor sets the username and password via in the constructor from the previous class above.
    Java Code:
    public class DataBaseConnection {
    
    	private Connection conn = null;
    	private String URL = "jdbc:mysql://localhost/employee";
    	private String userName = "";
    	private String passWord = "";
    	private UserPromptScreen screen;
    
    	public DataBaseConnection() {
    
    		this.passWord = screen.getPassWord();
    		this.userName = screen.getuserName();
    
    		connect();
    	}
    I attempt to connect but I get a NULL error before I do:
    Java Code:
    // Establish connection
    	void connect() {
    
    		// run driver
    		try {
    			Class.forName("com.mysql.jdbc.Driver");
    		} catch (ClassNotFoundException e) {
    			System.out.println("Error 1: Could not load driver");
    			e.printStackTrace();
    		}
    
    		// connecting to database
    		System.out.println("Connecting..");
    		try {
    			
    			setConnection(DriverManager.getConnection(URL, userName, passWord));
    			
    			if (!getConnection().isClosed()) {
    				System.out.println("Connected");
    			
    				// closing down login screen
    				screen.killProgram();
    				
    				// create the main GUI once you are in database
    				new MainMenuGUI();
    
    			}
    			// count not connect to database
    		} catch (SQLException e) {
    			// Custom button text
    			Object[] options = { "Yes", "No", "Close!" };
    			int n = JOptionPane.showOptionDialog(null,
    					"ERROR 2: You have enter in a incorrect user name or password.\n "
    							+ "Would you like to try again?",
    					"A Silly Question", JOptionPane.YES_NO_CANCEL_OPTION,
    					JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
    
    			if (n == 0) {
    
    			} else if (n == 1) {
    				// closing login screen
    				screen.killProgram();
    			} else if (n == 2) {
    				// closing login screen
    				screen.killProgram();
    			}
    			System.out.println("Error 2: Unable to connect to database"
    					+ ". Please check your username and password...");
    			e.printStackTrace();
    		}
    	}
    If I pass in the UserPromptScreen class it works but locks and never runs killProgram from the UserPromptScreen class:

    Java Code:
    void killProgram(){
    		
    		System.out.println("I was called");
    		frame.setVisible(false); //you can't see me!
    		frame.dispose(); //Destroy the JFrame object
    	}
    If you did not understand me. I have to do the following
    Java Code:
    public DataBaseConnection(UserPromptScreen screen) {
    		this.screen = screen;
    		this.passWord = screen.getPassWord();
    		this.userName = screen.getuserName();
    
    		connect();
    	}
    I have to pass in UserPromptScreen in for it to work. This will cause me issues later with my design.
    Last edited by jocdrew21; 02-19-2015 at 07:03 PM.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,143
    Rep Power
    15

    Default Re: getting values from one class to another without passing into it

    The bottom line is: you have to pass references around somehow. You've got the solution here, passing an instance of UserPromptScreen into your DataBaseConnection class. You say this will cause you issues: what issues?

    You *have* to pass instances around to share data between different instances. There isn't a way around that. Which instances you pass around is entirely up to you, but if you're asking for a way around passing them at all, you aren't going to find one.
    How to Ask Questions the Smart Way
    Static Void Games - GameDev tutorials, free Java and JavaScript hosting!
    Static Void Games forum - Come say hello!

  3. #3
    jocdrew21 is offline Senior Member
    Join Date
    Jan 2014
    Posts
    137
    Rep Power
    0

    Default Re: getting values from one class to another without passing into it

    It will not cause a problem if I am able establish/pass the connection to other classes through dependency injection like so:

    Java Code:
    public class MySQLDataBaseDAO implements DatabaseDAO {
    	
    	Connection connection;
    	PreparedStatement stmt = null;
    	ResultSet resultSet = null;
    	
    	String firstName,lastName,address;
    	int age;
    	
    	JFrame frame;
    	JOptionPane pane;
    	
    	Connection conn;
    		
    	public MySQLDataBaseDAO(Connection conn){
    		this.conn = connection;
    	}
    
    	public void insert(Person person) {
    		
    		firstName = person.getFirst();
    		lastName = person.getLast();
    		address = person.getAddress();
    		age = person.getAge();
    		
    		//need to add single quotes into statement
    		String query = "INSERT INTO guest"
    				+ "(first,last,age,address)"
    				+ "values(\'"+firstName+"\',\'"+lastName+"\',\'"+age+"\',\'"+address+"\')";
    		
    		System.out.println("Trying to add person");
    		
    		try {
    			connection.prepareStatement(query);
    			//stmt.execute(query);
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    Well that look good but it causes an error because this is one of the classes that passes the Connection to it.
    Java Code:
    public class AddUserPanelController {
    	
    	MainMenuGUI main;
    	DataBaseConnection dataBaseConnection; 
    	Connection conn = dataBaseConnection.getConnection();
    	
    	MySQLDataBaseDAO dataBase = new MySQLDataBaseDAO(conn);
    	Person person;
    	
    
    	String firstName,lastName, address, age;
    	
    	AddUserPanelController(MainMenuGUI main){
    		
    		this.main = main;
    		
    		listeners();
    	}
    
    private void listeners(){
    		main.addUserBtn.addActionListener(new ActionListener(){
    
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				
    				if(e.getSource().equals(main.addUserBtn)){
    					
    					firstName = main.firstNametxtAdd.getText();
    					lastName = main.lastNametxtAdd.getText();
    					address = main.addresstxtAdd.getText();
    					age = main.ageAdd.getText();
    					
    					person.setFirst(firstName);
    					person.setLast(lastName);
    					person.setAddress(address);
    					int ageInt = Integer.parseInt(age);
    					person.setAge(ageInt);
    					
    					System.out.println("Adding..");
    					System.out.println(person.getFirst()+" "+person.getLast()+
    							" "+person.getAddress()+" "+person.getAge());
    					
    					dataBase.insert(person);
    					
    				}
    				
    			}
    			
    		});
    Am I being clear or shall I explain more?

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,143
    Rep Power
    15

    Default Re: getting values from one class to another without passing into it

    You're still not dealing with the fundamental problem: when is DataBaseConnection created?

    You might also want to look into the idea of a singleton: Singleton pattern - Wikipedia, the free encyclopedia
    How to Ask Questions the Smart Way
    Static Void Games - GameDev tutorials, free Java and JavaScript hosting!
    Static Void Games forum - Come say hello!

  5. #5
    jocdrew21 is offline Senior Member
    Join Date
    Jan 2014
    Posts
    137
    Rep Power
    0

    Default Re: getting values from one class to another without passing into it

    I sincerely thank you but that leads me to another question:

    First the login screen is displayed:
    Java Code:
    public UserPromptScreen() {
    		//shows prompt screen
    		displayScreen();
    		//action listener for JButton
    		listener();
    	}
    The listener will try to validate it and connect it to the database

    Java Code:
    void vaildate() {
    		
    		setuserName(userText.getText());
    		setPassWord(passwordText.getText());
    		DataBaseConnection db = DataBaseConnection.getInstance();
    		//attempting to connect to database
    		db.connect();	
    	}
    	
    	private void listener(){
    		btn.addActionListener(new ActionListener(){
    
    			
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				System.out.println("Inside action");
    				if (e.getSource() == btn) {
    					vaildate();
    				}
    				
    			}
    			
    		});
    	}
    Java Code:
    public class DataBaseConnection {
    	
    	private static DataBaseConnection instance = new DataBaseConnection();
    	private static Connection conn = null;
    	private String URL = "jdbc:mysql://localhost/employee";
    	private String userName = "";
    	private String passWord = "";
    	private UserPromptScreen screen = new UserPromptScreen();
    
    	private DataBaseConnection() {
    		
    		this.passWord = screen.getPassWord();
    		this.userName = screen.getuserName();
    		
    	}
    	
    	public static DataBaseConnection getInstance(){
    		return instance;
    	}
    Now even after I put in the correct username and password it will not connect. This is where I am getting confused and thats why I tried to pass in a reference of the class originally.

  6. #6
    jocdrew21 is offline Senior Member
    Join Date
    Jan 2014
    Posts
    137
    Rep Power
    0

    Default Re: getting values from one class to another without passing into it

    I changed a few things around. I added getters and setters to the DataBase Class to set the username and password via the instance of the class with the skeleton method.
    Java Code:
    void vaildate() {
    		
    		setuserName(userText.getText());
    		setPassWord(passwordText.getText());
    		DataBaseConnection db = DataBaseConnection.getInstance();
    		//attempting to connect to database
    		db.setUserName(getuserName());
    		db.setPassWord(getPassWord());
    	}

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    26

    Default Re: getting values from one class to another without passing into it

    Moved from AWT/Swing to New to Java.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #8
    jocdrew21 is offline Senior Member
    Join Date
    Jan 2014
    Posts
    137
    Rep Power
    0

    Default Re: getting values from one class to another without passing into it

    Ok i figure it out but this leads me to security questions. In the below code I call the connect method which connects to the database. I wanted to make this a private method and call it in the database constructor but it was not working.
    Java Code:
    void vaildate() {
    
    		setuserName(userText.getText());
    		setPassWord(passwordText.getText());
    		DataBaseConnection db = DataBaseConnection.getInstance();
    		// setting database fields
    		db.setUserName(getuserName());
    		db.setPassWord(getPassWord());
    		db.connect();
    		
    		System.out.println(db.getUserName() + " " + db.getPassWord());
    	}
    Do you have advice on how to handle this? Seem unsafe if I can call the actual database connection and not the getter or getConnection like I planned.

  9. #9
    jocdrew21 is offline Senior Member
    Join Date
    Jan 2014
    Posts
    137
    Rep Power
    0

    Default Re: getting values from one class to another without passing into it

    Nevermind I think I got it!!!!!!!!!!!!

  10. #10
    jocdrew21 is offline Senior Member
    Join Date
    Jan 2014
    Posts
    137
    Rep Power
    0

    Default Re: getting values from one class to another without passing into it

    [SOLVED]

    Singleton Method, thank you for that.

Similar Threads

  1. Passing values and objects
    By jmohandos304 in forum New To Java
    Replies: 33
    Last Post: 11-10-2014, 02:51 PM
  2. Help needed in Passing values to another program.
    By Kuttappu in forum New To Java
    Replies: 3
    Last Post: 05-28-2012, 06:28 PM
  3. Arrays and passing values to methods help please.
    By toppcon in forum New To Java
    Replies: 21
    Last Post: 07-28-2011, 05:05 AM
  4. Passing the Values
    By Lagarto in forum JDBC
    Replies: 1
    Last Post: 07-16-2007, 03:03 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
  •