Evento de clic de botón en Java
    
    Sheeraz Gul
    12 octubre 2023
    
    Java
    Java Button
    
 
Usamos un detector de eventos para crear un evento de clic de botón en Java. Este tutorial demuestra cómo crear un evento de clic de botón en Java.
Evento de clic de botón en Java
Crear un evento de clic de botón en Java es un proceso paso a paso.
- 
Importe todos los paquetes requeridos, particularmente elJava.awt.event.
- 
Cree una claseMaindesde la que se llamará al evento.
- 
Cree otra clase que incluirá el objeto de la claseJFrame, los métodos definidos por el usuario y el constructor.
- 
Lo siguiente es agregar el botón aJFramey crear un objeto de la claseJButton.
- 
Lo siguiente es implementar la interfazactionListener.
- 
Finalmente, registramos elactionListeneral botón.
Intentemos implementar un ejemplo que cambiará de color al hacer clic en Java. Ver ejemplo:
package delftstack;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ActionEventDemo implements ActionListener {
  JFrame Demo_Frame = new JFrame();
  JButton Demo_Button = new JButton("Click Here");
  ActionEventDemo() {
    Prepare_GUI();
    Button_Properties();
  }
  public void Prepare_GUI() {
    Demo_Frame.setTitle("Demo Window");
    Demo_Frame.getContentPane().setLayout(null);
    Demo_Frame.setVisible(true);
    Demo_Frame.setBounds(400, 100, 400, 400);
    Demo_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public void Button_Properties() {
    Demo_Button.setBounds(150, 200, 150, 80);
    Demo_Frame.add(Demo_Button);
    Demo_Button.addActionListener(this);
  }
  @Override
  public void actionPerformed(ActionEvent e) {
    // Changing Background Color
    Demo_Frame.getContentPane().setBackground(Color.red);
  }
}
public class On_Click {
  public static void main(String[] args) {
    new ActionEventDemo();
  }
}
El código anterior creará un marco con el botón, que cambiará el color al hacer clic. Ver salida:

        ¿Disfrutas de nuestros tutoriales? Suscríbete a DelftStack en YouTube para apoyarnos en la creación de más guías en vídeo de alta calidad. Suscríbete
    
Autor: Sheeraz Gul
    Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook