Add actionListener to JButton dynamically

I have this code, which generates a window with a button.

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class PruebasGraficas {

    public static void main(String[] args) {

        JFrame Ventana1 = new JFrame();

        Ventana1.setTitle("VENTANA 1");
        Ventana1.setSize(300, 300);
        Ventana1.setLocation(500, 300);
        Ventana1.setVisible(true);
        JButton boton1 = new JButton();
        boton1.setText("EXECUTE");
        boton1.setVisible(true);
        Ventana1.getContentPane().setLayout(new FlowLayout());
        Ventana1.add(boton1);

    }

}

I would like to know which way would be more correct to add an action to the button dynamically.

In this case, that by pressing on the button, it executes an action.

enter the description of the image here

 1
Author: Ivan Botero, 2017-03-05

2 answers

You could do something like this:

package Interfaz;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class PruebasGraficas {

    public static void main(String[] args) {

        JFrame Ventana1 = new JFrame();

        Ventana1.setTitle("VENTANA 1");
        Ventana1.setSize(300, 300);
        Ventana1.setLocation(500, 300);
        Ventana1.setVisible(true);

        JButton boton1 = new JButton();
        boton1.setText("EXECUTE");
        boton1.setVisible(true);


        /* Asignamos una Accion al JButton */
        boton1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Saludos StackOverflow!");
            }

        });

        Ventana1.getContentPane().setLayout(new FlowLayout());
        Ventana1.add(boton1);
        Ventana1.revalidate();
    }

}
 1
Author: Ivan Botero, 2017-03-05 20:56:43

You Need a JButton listener (addActionListener), this defines what should be done when the user performs a certain action.

Example:

JButton btnEjemplo = new JButton("Clic aqui");
        btnEjemplo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                // aquí el código que quieres ejecutar cuando el botón sea presionado
                System.out.println("Hellow World!");
            }
        });
        btnEjemplo.setBounds(158, 109, 97, 25);

Everything you type inside, will be executed immediately when you click the button.

 1
Author: RRGT19, 2018-02-15 14:28:54