Question

I just have a very basic question about how to use textfields in Java. It's very simple, but the tutorials and other questions I've been looking for haven't been helpful, and I'm hoping that someone can explain things a little more clearly for me.

Right now I have the following code that I just sort of slapped together for the sake of example:

import javax.swing*;
public class testText {
    public static void main(String[] args){

        JFrame frame = new JFrame();
        JTextField text = new JTextField();
        frame.add(text);
        frame.setVisible(true);
        System.out.println(text.getText());
    }
}

All I'm trying to do, is print what the user types into the text field in the console. But nothing happens when I type into the text field.

Now,based on the research I've done, I think the problem is that I'm not using an actionListener. The thing is, I really don't understand how those work, and I'm hoping someone can clarify for me.

I've been using this tutorial to try and figure things out, and particularly the TextDemo example they have near the top. I'm still kind of at a loss though, and I can't seem to find any way to use the actionlistener interface without breaking the program. If someone could either just explain simply and directly how to use the actionlistener to pull a string from a text field and then use it, or else point me to somewhere else where I can FIND a simple straightforward explanation, I would immensely appreciate it. I've been beating my head against this for five hours now with absolutely nothing to show for it, so I apologize for asking such a basic question but I'm at a loss.

Was it helpful?

Solution

An action listener will be called when an enter key is pressed while typing in the field. From the JTextfield Javadoc :

How the text field consumes VK_ENTER events depends on whether the text field has any action listeners. If so, then VK_ENTER results in the listeners getting an ActionEvent, and the VK_ENTER event is consumed.

Here is your example modified to work with an action listener :

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

import javax.swing.JFrame;
import javax.swing.JTextField;

public class testText {
    public static void main(String[] args){

        JFrame frame = new JFrame();
        final JTextField text = new JTextField();
        frame.add(text);
        frame.setVisible(true);

        text.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(text.getText());
            }
        });
    }
}

And here is an object oriented complete example not relying only on a static main method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top