'm trying to pass a String from one class to another class but the result I'm getting is 'null'. I want to pass the String username from LoginFrame to HomeworkFrame;


public void loadSubjects (){
    String item;
        Scanner f = new Scanner (new FileReader (username + " " + "Subjects" + ".txt"));
            item = f.nextLine();
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "Subjects cannot be loaded!", "Error", JOptionPane.ERROR_MESSAGE);


public void loginUser(){
    r = new Registration();
    h = new HomeworkFrame();
    l = new Login();

    l.username = txtUser.getText();
    l.password = txtPass.getText();
        String line;
        boolean passwordFound = false ;
        BufferedReader f = new BufferedReader(new FileReader(l.username + ".txt"));
        while((line = f.readLine()) != null){
                passwordFound = true;

                h.username = l.username;
                JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);

Obviously I'm getting the error "Subjects cannot be loaded" as the username is null(I checked it by using the println method).

Thanks in advance

Re: Pass a String from one class to another - JAVA 80 80

I'm getting the error "Subjects cannot be loaded"

The code should always call the printStackTrace() method in catch blocks so you get the full text of the error message.

Where does the code assign a value to the variable that has a null value? Is the assignment done before the code tries to use it? Try debugging the code by adding some println statements to print out its value when it is assigned a value and when it is used.

Re: Pass a String from one class to another - JAVA 80 80

Can you post the complete code as i dint get where exactly you were calling the method "loadSubjects()" from LoginFrame ..

Re: Pass a String from one class to another - JAVA 80 80

I am guessing you are thinking that h.username = l.username; would automatically create a new String object from Login object and store in HomeworkFrame object. I believe that the value is disposed when you do dispose(). One way to try and see if that might be the cause is to add a method to add user name.

// in HomeworkFrame
public void addUsername(String uname) { username = uname; }

// when call

Hope this help...

Be a part of the DaniWeb community

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