Hi,

ive been trying to assign a value to a variable from within the ActionPerformed method, but the value seems to be lost as soon as ActionPerformed method ends. here's the code

public class Log{
private JTextField user = new JTextField(10);
private JPasswordField pass = new JPasswordField(10);
private int usertype=0;
private JPanel panel = new JPanel();

public Log(){

        panel.add(user);
        panel.add(pass);
        panel.add(button);

button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
              Login logs = new Login(user.getText(), pass.getText());
              //this one is querying the database and getting an int value for user type. 
                usertype = logs.getUsertype();
            }
        });
//some more codes to add to frame and stuff

}
public int getUserType(){
 return usertype;
 }
}

When I call the getUserType method, it always returns 0. i've checked if the usertype is assigned any value within the ActionPerformed method and it does. what am i doing wrong here?

thanks in advance

In actionPerformed, you create a new "Login", not a new "Log". Why didn't you post your Login class? (Post it :) )

PS: It seems to me from the way that you created a new "Login" and then called a method identical to one I see in the Log class, that Login extends Log, and that in the Login class, you did not override the getUserType method. But that's just a guess. I'm pretty sick right now, but post your class and someone will take a look at it.

In actionPerformed, you create a new "Login", not a new "Log". Why didn't you post your Login class? (Post it :) )

PS: It seems to me from the way that you created a new "Login" and then called a method identical to one I see in the Log class, that Login extends Log, and that in the Login class, you did not override the getUserType method. But that's just a guess. I'm pretty sick right now, but post your class and someone will take a look at it.

thanks mate,
nope, Log is not an extension of Login class, in fact, Log actually extends JInternalFrame, here is the two classes.

log class

public class LogUI extends JInternalFrame{
    private JTextField user = new JTextField(10);
    private JPasswordField pass = new JPasswordField(10);
    private JPanel panel = new JPanel();
    private JButton button = new JButton("Login");
    private int usertype;
    
public LogUI(){
        panel.add(user);
        panel.add(pass);
        panel.add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              Login lg = new Login(user.getText(), pass.getText());
                usertype = lg.getUsertype();
            }
        });
        this.add(panel);
        this.setTitle("Login");
        this.pack();
        this.setVisible(true);
    }
    public int getUsertype() {
        return usertype;
    }

and the Login class

public class Login {
    private int usertype;
    private ResultSet rs;
    private Statement st; 
    public Login(String user, String pass){
        try{
            SgmDb db = new SgmDb();
            st = db.connectToDB().createStatement();
            String query = "SELECT username, password, userType FROM user WHERE username='"+user+"' AND password = '"+pass+"'";
            st.executeQuery(query);
            rs = st.getResultSet();
            while(rs.next()){
                usertype = Integer.parseInt(rs.getString("userType"));
            }
            rs.last();
            if(rs.getRow()==0){
                JOptionPane.showMessageDialog(null, "Wrong username or password");
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Contact Admin, there is a problem");

        }
    }
    public int getUsertype(){
        return this.usertype;
    }
}

check s:

String s = rs.getString("userType");
System.out.println("|"+s+"|");
usertype = Integer.parseInt(s);

check s:

String s = rs.getString("userType");
System.out.println("|"+s+"|");
usertype = Integer.parseInt(s);

hey thanks for ya reply. But I've already done this. In the Login class. see line 13.

usertype = Integer.parseInt(rs.getString("userType"));

and when i call to this value from Log class, see line 15 in class Log, I get the value. and if i print out the usertype within the actionPerformed method, the value is there. But if I call it outside this method, the value is not there. meaning I cannot retrieve the usertype value in the Log class.

say for example the following code.

Log logObject = new Log();
int x = logObject.getUserType();

// int x is always 0. this is my problem.

Hmm... try defining that 'ActionListener' outside the constructor.

Hmm... try defining that 'ActionListener' outside the constructor.

Wrong. Run my code if you don't believe me.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class RandomTest extends JPanel implements WindowListener{
	
	int random = 0;
	public RandomTest(){
		JButton button = new JButton("Click me");
		
		button.addActionListener(new ActionListener(){
		
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				random = 5;
				System.out.println("Variable random is " + random);
			}
		});
		this.add(button);
	}
	
	public static void main(String[] args){
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		RandomTest test = new RandomTest();
		frame.add(test);
		frame.addWindowListener(test);
		frame.setSize(300,300);
		frame.setVisible(true);
	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("Window is closing. Variable random  = " + random);
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	
}

Wrong. Run my code if you don't believe me.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class RandomTest extends JPanel implements WindowListener{
	
	int random = 0;
	public RandomTest(){
		JButton button = new JButton("Click me");
		
		button.addActionListener(new ActionListener(){
		
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				random = 5;
				System.out.println("Variable random is " + random);
			}
		});
		this.add(button);
	}
	
	public static void main(String[] args){
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		RandomTest test = new RandomTest();
		frame.add(test);
		frame.addWindowListener(test);
		frame.setSize(300,300);
		frame.setVisible(true);
	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		System.out.println("Window is closing. Variable random  = " + random);
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	
}

oi mate, thanks for the reply. i see that the value is maintained in ur code, but im still having trouble figuring out what I have done wrong. could you point me in a bit more like "idiots guide to.." style :D thannks

Ok.

usertype = logs.getUsertype();
System.out.println(usertype);

If you do that in your actionPerformed, then you print userType from within another method, after you have clicked on your button, then you will see that usertype changed. The problem you are having is that you must have done something like this:

button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
              Login logs = new Login(user.getText(), pass.getText());
              //this one is querying the database and getting an int value for user type. 
                usertype = logs.getUsertype();
            }
        });
//some more codes to add to frame and stuff

System.out.println(usertype); //WILL ALWAYS PRINT 0

}

usertype (in the println that I commented next to) will always print 0 because it is in the constructor. You added an action listener to the button, but you didn't click the button yet. So after the code I posted above adds the action listener, it immediately goes and prints "usertype" - but you haven't clicked the button yet, and therefore usertype has not been changed yet, so it prints 0!

Basically, I don't think you don't have a problem, you just think you have a problem. If you *really* want to verify that "usertype" is being set correctly, just do a System.out.println(getUsertype()); inside of the actionPerformed method at some point after you set the usertype.

Usage of LogUI and Login:

/**
 *
 * @author j3c
 */
public class Starter extends JFrame {

    public Starter() {

        final LogUI logUI = new LogUI();

        JPanel panel = new JPanel();
        final JLabel label = new JLabel("usertype");
        JButton button = new JButton("get login");
        panel.add(label);
        panel.add(button);
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                label.setText("" + logUI.getUsertype());
            }
        });
        add(panel);
        setTitle("Starter");
        setDefaultCloseOperation(3);
        pack();
        setLocationRelativeTo(null);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new Starter();
    }
}
package kekkaishi;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

class LogUI extends JFrame {

    private JTextField user = new JTextField(10);
    private JPasswordField pass = new JPasswordField(10);
    private JPanel panel = new JPanel();
    private JButton button = new JButton("Login");
    private int usertype;

    public LogUI() {
        panel.add(user);
        panel.add(pass);
        panel.add(button);
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //Login lg = new Login(user.getText(), pass.getText());// getText -->deprecated
                Login lg1 = new Login(user.getText(), pass.getPassword());
                usertype = lg1.getUsertype();
                int i = getUsertype();
                System.out.println("LogUI i=" + i);
            }
        });
        this.add(panel);
        this.setTitle("Login");
        this.pack();
        this.setDefaultCloseOperation(3);
        this.setVisible(true);
    }

    public int getUsertype() {
        System.out.println("LogUI getUsertype()" + usertype);
        return usertype;

    }

    public static void main(String[] args) {
        LogUI lo = new LogUI();
        System.out.println(lo.getUsertype());
        System.out.println("end of main(...)");
        ///}
        // but
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                //
            }

            System.out.println(lo.getUsertype());
        }
    }
}
package kekkaishi;

//import java.sql.*;
//import javax.swing.JOptionPane;
public class Login {

    private int usertype;
    //private ResultSet rs;
    //private Statement st;

    public Login(String text, char[] password) {
        ///..............simplified
        usertype = text.length();// to view result dependent of human action
    }

    public int getUsertype() {
        System.out.println("Login getUsertype()" + usertype);
        return this.usertype;
    }
}

start both main(..)
//////////////////////
Other expected behavior requires changes in the code

Ok.
usertype (in the println that I commented next to) will always print 0 because it is in the constructor. You added an action listener to the button, but you didn't click the button yet. So after the code I posted above adds the action listener, it immediately goes and prints "usertype" - but you haven't clicked the button yet, and therefore usertype has not been changed yet, so it prints 0!

Basically, I don't think you don't have a problem, you just think you have a problem. If you *really* want to verify that "usertype" is being set correctly, just do a System.out.println(getUsertype()); inside of the actionPerformed method at some point after you set the usertype.

with all due respect mate, and i'm sure its annoying as hell to listen to one person like me babbling all day, I have done all these. That System.out.println(usertype) or System.out.println(getUsertype) was added inside actionPerformed to check if the value is there and it is. I think i havent clarified my exact problem here.
In the Main class I am creating a new object of LogUI, say logUI object, and am adding it to the desktopPane. Now i see two text fields and a button as expected. I am entering a correct username n a password and then I click the button. Now, my expected outcome is the button is setting the usertype in the LogUI class and if I call the logUI.getUsertype(), i am expecting it to have maintained the usertype assigned when I pressed the button.
oh man... this problem has driven me, dunno from stupid to stupider. I should try another method of doing it.
So anyways, thanks to all of you who tried to help. really I appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.