Agregue ActionListener a JButton en Java
-
Agregue
ActionListenera unJButtonusando una clase anónima -
Agregue
ActionListeneraJButtonusando Anonymous Class y Lambda -
Agregue
ActionListeneraJButtonusando herencia
Hoy discutiremos la interfaz ActionListener del java.awt.event y cómo agregarlo a un JButton, un componente de la clase JFrame en el paquete Java Swing.
Agregue ActionListener a un JButton usando una clase anónima
En el primer ejemplo, creamos una clase JavaExample con un método main(), y en ese método creamos un objeto JFrame. En la ventana JFrame, creamos tres componentes: un JLabel para mostrar un mensaje, un JTextField para tomar una entrada y un JButton al que agregaremos el ActionListener.
Para agregar el oyente, llamamos a la función addActionListener() de la clase JButton, y en este método, creamos una clase anónima y anulamos la función actionPerformed() que forma parte de la interfaz ActionListener. actionPerformed() es un método que se llama cuando se realiza una acción.
En el método actionPerformed(), primero comprobamos si hay algo en el JTextField, y si el campo de texto está vacío, mostramos un mensaje usando JLabel. De lo contrario, mostramos el mensaje que escribimos en el Campo de texto.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaExample {
public static void main(String[] args) {
JFrame jFrame = new JFrame("Java Example");
JLabel jLabel = new JLabel();
jLabel.setBounds(50, 150, 350, 40);
final JTextField jTextField = new JTextField();
jTextField.setBounds(50, 50, 150, 20);
JButton jButton = new JButton("Submit");
jButton.setBounds(50, 100, 100, 30);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!jTextField.getText().equals(""))
jLabel.setText(jTextField.getText());
else
jLabel.setText("Please write something in the edit box");
}
});
jFrame.add(jLabel);
jFrame.add(jButton);
jFrame.add(jTextField);
jFrame.setSize(400, 400);
jFrame.setLayout(null);
jFrame.setVisible(true);
}
}
Producción:

Agregue ActionListener a JButton usando Anonymous Class y Lambda
En Java 8, se agregaron expresiones Lambda que usaríamos en este ejemplo. Todo es igual al ejemplo anterior, pero en el programa creamos un método buttonPressed(), y en esa función imprimimos el mensaje escrito en el campo de texto a un JLabel.
Para agregar el ActionListener al JButton, usamos la función addActionListener(), y en ese método, usamos el enfoque lambda. Usamos el parámetro e que es un objeto ActionEvent, luego llamamos al método buttonPressed().
import javax.swing.*;
public class JavaExample {
static JTextField jTextField;
static JLabel jLabel;
public static void main(String[] args) {
JFrame jFrame = new JFrame("Java Example");
jLabel = new JLabel();
jLabel.setBounds(50, 150, 350, 40);
jTextField = new JTextField();
jTextField.setBounds(50, 50, 150, 20);
JButton jButton = new JButton("Submit");
jButton.setBounds(50, 100, 100, 30);
jButton.addActionListener(e -> buttonPressed());
jFrame.add(jLabel);
jFrame.add(jButton);
jFrame.add(jTextField);
jFrame.setSize(400, 400);
jFrame.setLayout(null);
jFrame.setVisible(true);
}
static void buttonPressed() {
if (!jTextField.getText().equals("")) {
jLabel.setText(jTextField.getText());
} else {
jLabel.setText("Please write something in the edit box");
}
}
}
Producción:

Agregue ActionListener a JButton usando herencia
En este programa, agregamos el ActionListener usando el concepto de herencia.
Creamos una clase JavaExample y luego extendemos la clase JFrame e implementamos la interfaz ActionListener. Tenemos que anular el método actionPerformed() que forma parte de la interfaz ActionListener.
Declaramos las variables del componente JFrame fuera del método main() porque necesitamos usarlo fuera de la función. Creamos un constructor de la clase JavaExample y configuramos todos los componentes en él.
Para agregar el ActionListener al componente JButton, llamamos al método addActionListener() y pasamos this, que apunta al contexto de la clase actual como la clase actual JavaExample implementa ActionListener es un contexto válido para pasar la función.
En la función actionPerformed() escribimos las operaciones que queremos realizar cuando se pulsa el botón. En el método main(), creamos una instancia de JFrame y establecemos su diseño y visibilidad.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaExample extends JFrame implements ActionListener {
static JTextField jTextField;
static JLabel jLabel;
static JButton jButton;
public static void main(String[] args) {
JFrame jFrame = new JavaExample();
jFrame.setLayout(null);
jFrame.setVisible(true);
}
public JavaExample() {
jLabel = new JLabel();
jLabel.setBounds(50, 150, 350, 40);
jTextField = new JTextField();
jTextField.setBounds(50, 50, 150, 20);
jButton = new JButton("Submit");
jButton.setBounds(50, 100, 100, 30);
jButton.addActionListener(this);
add(jLabel);
add(jButton);
add(jTextField);
setSize(400, 400);
}
@Override
public void actionPerformed(ActionEvent e) {
if (!jTextField.getText().equals("")) {
jLabel.setText(jTextField.getText());
} else {
jLabel.setText("Please write something in the edit box");
}
}
}
Producción:

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedInArtículo relacionado - Java Swing
- Componente de pintura Java
- Uso de SwingUtilities.invokeLater() en Java
- Campo de texto claro de Java
- Crear lienzo usando Java Swing
- Cambiar el texto JLabel en Java Swing
- Centrar una JLabel en Swing
