You can add an ActionListener to a JTextField in Java by calling the addActionListener() method, passing in an instance of a class that implements the ActionListener interface, like this:
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Text entered: " + textField.getText());
}
});
Here is an example program that demonstrates some of these concepts:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(200, 20));
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Text entered: " + textField.getText());
}
});
frame.add(textField);
frame.pack();
frame.setVisible(true);
}
}
This program creates a JFrame with a JTextField that has a preferred size of 200 pixels by 20 pixels. It also adds an ActionListener to the JTextField that prints out the text entered whenever the user presses the "Enter" key.