You can pass the required field in the builder:
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 below, 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);
}
}
very good answer, about the second method has some link that can indicate with some further explanation?
– leandroungari
@leandro17br See if this link helps you: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html - If it doesn’t help, just search Google for "java lambda-Expressions" and you should find plenty of things.
– Victor Stafusa