Search code examples
javavariablesuser-interfacejframejtextfield

JTextField's getText() to printable variable


I've just taken up playing with GUIs, and I'm experimenting with getting text input from the user, and assigning it to a variable for later use.

Easy, I thought. Wrong, I was.

I wanted my frame to look something like:

public class firstFrame extends JFrame {

JTextField f1 = new JTextField();
String text;

public firstFrame(String title) {
    super(title);

    setLayout(new BorderLayout());

    Container c = getContentPane();

    c.add(f1);

    text = f1.getText();

    System.out.println(text);
    }
}

Where the variable text would get whatever text the user typed in, then print it out to the console. Simple.

I've got a feeling I'm missing something pretty fundamental here, and would appreciate it if anyone could fill me in on what that something is.


Solution

  • getText() only get the text that is in the JTextArea at the time it is called.

    You are calling it in the constructor. So when you instantiate new firstFrame, there is no initiital text.

    One thing to keep in mind is that GUIs are event driven, meaning you need an event handler to capture and process events.

    One option is to add an ActionListener to the JTextField so when you press Enter after entering text, the text will print.

    f1.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = f1.getText();
            System.out.println(text);
        }
    });
    

    See more at how to Create GUI with Swing and Writing Event Listeners