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;
}
}