简体   繁体   中英

Variable's value doesn't change to the new one specified in the actionListener

so I created a variable called savedName and then set the value of this to a new value in the action listener method. It prints the changed value in the action listener but ONLY in the action listener. It seems like once the action listener has taken place, the variable's value is changed back to "null" (the default value). The username_txt is a text field into which the user enters information. But as I stated, the value is only changed temporarily in the action Listener method it seems like and once the action listener has taken place, it changes back to the default value. I have bolded the statements for savedName.

public class LoginWindow extends javax.swing.JFrame {

    /**
     * Creates new form LoginWindow
     */
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;
    **private String savedName;**
    public LoginWindow() {
        initComponents();
        conn = JavaConnect.ConnecrDb();
    }
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    String user_sql = "select * from Users where Username=? and Password=? ";
    try{
        pst = conn.prepareStatement(user_sql);
        pst.setString(1, username_txt.getText());
        savedName = username_txt.getText();
        System.out.println(savedName);
        pst.setString(2, password_txt.getText());

        rs = pst.executeQuery();
        if(rs.next()){
            JOptionPane.showMessageDialog(null, "Wecome!");
            rs.close();
            pst.close();
            this.dispose();

            UserMainWindow wind = new UserMainWindow();
            wind.setVisible(true);
        }
        else{
            JOptionPane.showMessageDialog(null, "Username and/or Password is not correct");
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null,e);
    }
    finally {
        try{
        rs.close(); 
        pst.close();
        }
        catch(Exception e){

        }
     }
}                

Note : I cant comment my thoughts so i just post it as an answer :) comment below for me to update my answer.

After the jButton2ActionPerformed what will happen? it will leave in LoginWindow class and go to another class or not ? if yes then the value of your String savedName will return to null.

Instance variables are declared in a class, but outside a method. They are also called member or field variables. When an object is allocated in the heap, there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed. Visible in all methods and constructors of the defining class, should generally be declared private, but may be given greater visibility. click here.

Here is my suggestion .

First :

Create a Class that has a instance variable of public static String savedName = "";

Eg

package com.sample.classes;
public class SampleClass {
    public static String savedName = "";
}

Then all the class that needed this Variable must extend it like

   public class Sample2 extends SampleClass{

      public void showUserName(){
        System.out.println(SampleClass.savedName);
      }

   }

public class Sample1 extends SampleClass{
    public void pressThisButton (String username){
        SampleClass.savedName = username;
    }

}

public static void main(String [] args){
    Sample1 press = new Sample1();
    // Populate the savedName variable 
    press.pressThisButton("My Name is Press");

    // access savedName variable.
    new Sample2().showUserName();

}

in this scenario you can still use the value of savedName even you already left on a certain class.

but im still not sure about this :), just comment if there's a correction TIA

You are getting null from the other class is because you are creating a new object rather then passing the value into the other class. This can be done by putting a constructor inside your UserMainWindow class and accepting a String for the name. If you already have a constructor just accept String as a parameter and create a variable for the string and set it..

example code : (NOTE this is the UserMainWindow class)

private String savedName;
public UserMainWindow(String savedName){
  this.savedName = savedName;
}

now in the class you are creating this object, pass it the string like this: (and this is the class you are creating the userMainWindow class)

UserMainWindow wind = new UserMainWindow(savedName);

Now you should have savedName saved inside your other frame (user main window) while the other frame is discarded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM