how to add a command to a button

how to add a command to a button

To add a command to a button in Java, you can use the addActionListener method of the javax.swing.JButton class. This method takes an instance of the java.awt.event.ActionListener interface as an argument, and registers the listener to receive action events from the button.

Here's an example of how you could use the addActionListener method to add a command to a button:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class Main {
  public static void main(String[] args) {
    JButton button = new JButton("Click me");

    // Add an action listener to the button
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        // This code will be executed when the button is clicked
        System.out.println("Button clicked");
      }
    });
  }
}
Sou‮:ecr‬www.lautturi.com

In this example, the addActionListener method registers an anonymous inner class as the action listener for the button. When the button is clicked, the actionPerformed method of the listener is called, and the code inside the method is executed.

You can customize the code inside the actionPerformed method to perform any action you want when the button is clicked. For example, you can update a label, display a message, or perform a calculation.

Keep in mind that the addActionListener method can only be used with buttons that support action events, such as JButton objects. If you want to add a command to a different type of component, you may need to use a different approach.

Created Time:2017-11-01 12:05:09  Author:lautturi