This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes Passing Value from 1 class 2 another Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Passing Value from 1 class 2 another" Watch "Passing Value from 1 class 2 another" New topic
Author

Passing Value from 1 class 2 another

Anand Karia
Ranch Hand

Joined: Sep 25, 2004
Posts: 156

Dear All

I m a new user of java.

plz help me out 2 solve my problem.

1 class = dbconnection
2 class = util
3 class = company
4 class = login

i ve connected database with dbconnection in login form using
dbconnection conn = new dbconnection();

then userid is asked. When i enter my login it passes value to util class
util u = new util(); // this is initialized at top.
u.setValue(txtUserId.getText());

public String setValue(String str)
{ String myVal
myVal = str;
System.out.println(myVal);
return myVal;
}

when i m trying to print that value i is showing user id.

I ve a button on login form called "Company".
I ve inititlized util object at the top.

util abc = new util();

Problem:
========
i want to get the value that i ve assigned in my login form using setValue() method.

But when ever i m getting value from util class it shows null value;
Plz tell where i m wrong?

ANAND


Love is GOD and GOD is Love.
Anand Karia
IT Concretor.......
M/s. Anand Karia Concreting IT
Dun Dagda
Ranch Hand

Joined: Oct 12, 2004
Posts: 54
Hi,
I'm not sure what your util class looks like, but I would put something like this in it:

class util {
private String myVal;

public void setValue(String str) {
this.myVal = str;
}

public String getValue() {
return myVal;
}
}

Basically, it seems you need an instance String variable to hold the value of your string within your util object. Calling getValue() on an instance of util should then return the String you want. Or is your code trying to do something fancier that I have not understood?


SCJP 1.4<br />SCWCD (in progress)
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

I'm going to move thi to the intermediate forum, where I think its a bit more appropriate. So please post your replies there. Thanks!
Ian Darwin
author
Ranch Hand

Joined: Aug 03, 2001
Posts: 64
It wasn't clear if you are writing a Swing app or a Web app. But the set/get method isn't how
we normally do things. There is a very well known "coding pattern" for methods that set and get fields. As was mentioned, this should be something like:

String myVal;
public void setValue(String str)
{
myVal = str;
}

public String getValue()
{
return myVal;
}

This is known as the "setter/getter" idiom. If you want to add print statements to the setter you can, for debugging purposes only however.

This idiom is so standard that most IDEs like Eclipse will generate them for you. Just create your
fields, and then go Source->Generate Setters/Getters, and select which ones you want it to write for you.

As to whether you need a separate class just to hold a String, probably not, but we'd need to know more about the overall design of your application.

Cheers
Ian


Ian Darwin
Many questions are answered in my Java Cookbook, 2nd Edition
Dun Dagda
Ranch Hand

Joined: Oct 12, 2004
Posts: 54
Ian,
Yes, this is just the same as what I already said. Obviously you would want the util class to do more than just hold a String. I don't know what Anand originally wanted the util class to do, as the full code wasn't posted, but I was just posting an example of what the class should contain in order to allow access to the String value required; clearly the class should contain a lot of other code besides that if it is a utility class for logging into a database.
Ko Ko Naing
Ranch Hand

Joined: Jun 08, 2002
Posts: 3178
This thread is a duplicated one of the past thread... So to eliminate the redundancy, we should post in only one thread(probably in this thread) and close the other one... :roll:


Co-author of SCMAD Exam Guide, Author of JMADPlus
SCJP1.2, CCNA, SCWCD1.4, SCBCD1.3, SCMAD1.0, SCJA1.0, SCJP6.0
Anand Karia
Ranch Hand

Joined: Sep 25, 2004
Posts: 156

What i want that is, when ever i click login button in login form. I want to set userid into util class. If i m going into another Company Form, at the load of company form, i want to getValue() from this util class.

I want suggestion that how can i setValue() when i m in login form that is extended by javax.swing.JFrame and How can i getValue() from util class when i m in Company Form also extended by javax.swing.JFrame.


Here is my dbConnection Class: and Login Form

////////////////////////////////////////
dbConnection.class
////////////////////////////////////////

import java.sql.*;


class dbConnection {
public Connection Conn ;
public Statement st,ss;
public ResultSet rs;
public String strUserID;
Statement ss=null;

/** Creates a new instance of Connection */
public dbConnection() {

try{
Class.forName("org.postgresql.Driver");
Conn = DriverManager.getConnection("jdbc ostgresql://199.194.195.110:5432/masterdb","postgres","postgres");
st = Conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE );
System.out.println("Connection Established.........");
}
catch(Exception e){
System.out.println("Connection mein panga hai bhai "+ e );
}
}

public ResultSet getConnection (String str) throws SQLException
{
ResultSet rs = st.executeQuery(str);
return rs;
}
public String setUserID(String str) throws SQLException
{ String cc;
strUserID = str;
cc = strUserID;
return cc;

}
}


///////////////////////////////////
HERE IS LOGIN CLASS
//////////////////////////////////

import javax.swing.*;
import java.awt.event.WindowEvent.*;
import java.sql.*;
public class Login extends javax.swing.JFrame {
public ResultSet rs ;
//dbConnection cnn = new dbConnection();
public String strUserID;
/** Creates new form Login */
public Login() {
initComponents();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
txtUserID = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtPassword = new javax.swing.JPasswordField();
lblStatus = new javax.swing.JLabel();
login = new javax.swing.JButton();
exit = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();

getContentPane().setLayout(null);

setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Login");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});

jLabel1.setFont(new java.awt.Font("Default", 1, 12));
jLabel1.setText("User ID");
getContentPane().add(jLabel1);
jLabel1.setBounds(40, 50, 60, 15);

txtUserID.setNextFocusableComponent(txtPassword);
txtUserID.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
txtUserIDFocusLost(evt);
}
});
txtUserID.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtUserIDKeyPressed(evt);
}
});

getContentPane().add(txtUserID);
txtUserID.setBounds(120, 50, 120, 19);

jLabel2.setFont(new java.awt.Font("Default", 1, 12));
jLabel2.setText("Password");
getContentPane().add(jLabel2);
jLabel2.setBounds(40, 80, 70, 15);

txtPassword.setBackground(new java.awt.Color(255, 204, 204));
txtPassword.setNextFocusableComponent(login);
getContentPane().add(txtPassword);
txtPassword.setBounds(120, 80, 120, 19);

lblStatus.setForeground(new java.awt.Color(255, 0, 0));
getContentPane().add(lblStatus);
lblStatus.setBounds(90, 180, 180, 20);

login.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/blueHome.png")));
login.setMnemonic('g');
login.setText("Go");
login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginActionPerformed(evt);
}
});

getContentPane().add(login);
login.setBounds(60, 130, 90, 32);

exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/redstop.png")));
exit.setMnemonic('x');
exit.setText("Exit");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});

getContentPane().add(exit);
exit.setBounds(150, 130, 90, 32);

jLabel6.setFont(new java.awt.Font("Default", 1, 12));
jLabel6.setLabelFor(lblStatus);
jLabel6.setText("Status:");
getContentPane().add(jLabel6);
jLabel6.setBounds(32, 180, 50, 15);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-331)/2, (screenSize.height-242)/2, 331, 242);
}

try{ System.out.println("Going to Check User");
String sql = "Select userid, pwd from user_manager where userid = '" + txtUserID.getText() + "' and pwd = '" + txtPassword.getText() + "'";
lblStatus.setText("Going Now");
////////////////
dbConnection cnn = new dbConnection();
Statement st = cnn.Conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE );
rs = st.executeQuery(sql);
if (rs.next()==false)
{
lblStatus.setText("No record found");
}
else{
rs.last();
if (rs.getString(1) == null)
{
System.out.println("No defined user is found");
lblStatus.setText("Invalid User ID ");
}
else
{
cnn.strUserID = txtUserID.getText();
Company_Year_Selection cd = new Company_Year_Selection();
cd.show();
setVisible(false);
cd.txtUserId.setText(txtUserID.getText());

}
}
///////////////
}
catch(Exception e){}

/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
new Login().show();
}

// Variables declaration - do not modify
private javax.swing.JButton exit;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel lblStatus;
private javax.swing.JButton login;
private javax.swing.JPasswordField txtPassword;
public javax.swing.JTextField txtUserID;
// End of variables declaration
}

/////////////////////////////////////////////////
 
Consider Paul's rocket mass heater.
 
subject: Passing Value from 1 class 2 another