You can pass the required field in the constructor:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public abstract class Teste {
public static void main(String[] args) {
JFrame tela = new JFrame("Teste");
JPanel panel = new JPanel();
JLabel texto = new JLabel("Nome: ");
JTextField nomeField = new JTextField(60);
panel.add(texto);
panel.add(nomeField);
Clique text = new Clique(nomeField);
nomeField.addActionListener(text);
panel.setLayout(new FlowLayout());
tela.setContentPane(panel);
tela.pack();
tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tela.setVisible(true);
}
}
class Clique implements ActionListener {
private final JTextField field;
public Clique(JTextField field) {
this.field = field;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(field.getText());
}
}
Another alternative is to use a lambda (Java 8 or higher):
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public abstract class Teste {
public static void main(String[] args) {
JFrame tela = new JFrame("Teste");
JPanel panel = new JPanel();
JLabel texto = new JLabel("Nome: ");
JTextField nomeField = new JTextField(60);
panel.add(texto);
panel.add(nomeField);
nomeField.addActionListener(event -> System.out.println(nomeField.getText()));
panel.setLayout(new FlowLayout());
tela.setContentPane(panel);
tela.pack();
tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tela.setVisible(true);
}
}
A third way, if you are in Java 7 or lower, is to use an anonymous class:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public abstract class Teste {
public static void main(String[] args) {
JFrame tela = new JFrame("Teste");
JPanel panel = new JPanel();
JLabel texto = new JLabel("Nome: ");
JTextField nomeField = new JTextField(60);
panel.add(texto);
panel.add(nomeField);
nomeField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println(nomeField.getText());
}
});
panel.setLayout(new FlowLayout());
tela.setContentPane(panel);
tela.pack();
tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tela.setVisible(true);
}
}