简体   繁体   中英

Why does my java variable return as null

Help my private string username returns null!

Okay, I made a JFrame window which contains a JTextField called usernameID, and a button called submit, when submit is clicked an actionlistener is called which calls the method setUsername() which sets private string username to equal to usernameID.getText(), once it was set.

So, my getUsername() returns the variable username, but when it is returned, the value which is returned is null, to me I think there is something wrong, I set the value of username to usernameID.getText() with my setUsername method.

So please help, how would I go abouts making the method called getUsername return what the user entered in usernameID?

Here is my code:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class GUI {
    private JFrame frame = new JFrame();
    private String user;

    GUI() {

        FlowLayout layout = new FlowLayout();
        JLabel usernameText = new JLabel("Username:");
        final JTextField usernameID = new JTextField(17);
        JButton submit = new JButton("Submit");

        frame.setTitle("Enter username");
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setSize(300, 100);
        frame.setAlwaysOnTop(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.requestFocus();
        frame.setLayout(layout);

        frame.add(usernameText);
        frame.add(usernameID);
        frame.add(submit);

        submit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                setUsername(usernameID.getText());

                frame.setVisible(false);
                frame.dispose();

            }

        });

    }

    private void setUsername(String text) {
        user = text;

    }

    String getUsername() {
        return user;
    }

}

This is the class that calls it.

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class Play extends BasicGameState {

        public Play(int state) {
        }

        @Override
        public void init(GameContainer gc, StateBasedGame sbg)
                        throws SlickException {
                gc.setShowFPS(false);

                @SuppressWarnings("unused")
                Player player = new Player(getName(), 100, 100);
        }

        private String getName() {
                GUI gui = new GUI();
                System.out.println("Username: "+gui.getUsername());
                return gui.getUsername();
        }

        @Override
        public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
                        throws SlickException {
        }

        @Override
        public void update(GameContainer gc, StateBasedGame sbg, int delta)
                        throws SlickException {
        }

        @Override
        public int getID() {
                // TODO Auto-generated method stub
                return 1;
        }
}

Tested your code and it runs fine. The user field get's properly set with the name you just entered.

Some reasons I could see are that you either call getUserName() too early (before SUBMIT has been pressed) or on a different instance of GUI . The problem is definetly in the "other parts" of your code

You are doing everything the right way, your problem is when you are trying to call the value of your user variable.

     new GUI();
     System.out.println(user);

will deliver null because it will first get the value you inserted after you click your button.

I tried your code and the variable is getting the value.

You must know your UI is on another thread and thats why if you try something with the code without waiting for the submission it will be null

Based on my assessment of that code (which was not an SSCCE, therefore this might be wrong), I can guess that you are using the JFrame when you should actually be using a modal JDialog or a JOptionPane .

They will 'block' until closed, at which point, the value should not be null .

        private String getName() {
                GUI gui = new GUI();
                System.out.println("Username: "+gui.getUsername());
                return gui.getUsername();
        }

Yep. That about seals it..

Other tips

  1. For better help sooner, post an SSCCE .
  2. See The Use of Multiple JFrames, Good/Bad Practice?

Fixed SSCCE

import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;

public class GUI {

    // add 'true' to ensure this is a blocking dialog.
    private JDialog frame = new JDialog((JFrame)null, true);
    private String user;

    GUI() {

        FlowLayout layout = new FlowLayout();
        JLabel usernameText = new JLabel("Username:");
        final JTextField usernameID = new JTextField(17);
        JButton submit = new JButton("Submit");

        frame.setTitle("Enter username");
        frame.setLocationRelativeTo(null);
        frame.setSize(300, 100);
        frame.setAlwaysOnTop(true);
        // Not allowed in a dialog..
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.requestFocus();
        frame.setLayout(layout);

        frame.add(usernameText);
        frame.add(usernameID);
        frame.add(submit);

        submit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                setUsername(usernameID.getText());

                frame.setVisible(false);
                frame.dispose();

            }

        });

        // as mentioned in a comment by mKorbel, this needs to be last
        frame.setVisible(true);
    }

    private void setUsername(String text) {
        user = text;

    }

    String getUsername() {
        return user;
    }

    public static void main(String[] args) {
        GUI gui = new GUI();
        System.out.println("Username: "+gui.getUsername());
    }

}

This is how you should do:

submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            setUsername(usernameID.getText());
            System.out.println(getUsername());

            frame.setVisible(false);
            frame.dispose();

        }

    });

}

Or it could be more better with this:

 submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            setUsername(usernameID.getText());
           JOptionPane.showMessageDialog(null, getUsername());

            frame.setVisible(false);
            frame.dispose();

        }

    });

}

At the moment you call getUserName there should be a already set user name, other wise it will return null . So setUserName before get.

Okay so, I changed it around.

public String getPlayerUsername() {

    String name;

    final JFrame frame = new JFrame();
    FlowLayout layout = new FlowLayout();
    final JLabel usernameText = new JLabel("Username:");
    final JTextField usernameID = new JTextField(17);
    JButton submit = new JButton("Submit");

    frame.setTitle("Enter username");
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    frame.setSize(300, 100);
    frame.setAlwaysOnTop(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.requestFocus();
    frame.setLayout(layout);

    frame.add(usernameText);
    frame.add(usernameID);
    frame.add(submit);
    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            frame.setVisible(false);
            frame.dispose();

            String name = usernameText.getText();

        }

    });
    return name;

}

I want it that when it returns name, it returns the value the user entered in usernameText, it doesn't work.

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