Technology Software

How to Use ActionListener in Java

    • 1). Launch your Java development program.

    • 2). Create a new class file by clicking on the "File" menu and selecting "New." Enter "ButtonActionListener.java" in the "File Name" field and save.

    • 3). Import the java.awt.event package by typing the following at the top of the file in the text editor:

      import java.awt.event.*;

      The java.awt.event package allows access to the ActionListener interface.

    • 4). Create the ButtonActionListener class and have it implement the ActionListener interface by typing the following in the text editor immediately after the package declaration:

      public class ButtonActionListener implements ActionListener {}

      The rest of the code for the class will be written inside the curly braces.

    • 5). Create a button called "button" by typing in the following code:

      JButton button = new JButton("Button label");

      Replace "Button label" with what you want the button to display.

    • 6). Add the ActionListener to the button by typing the following:

      button.addActionListener(this);

      An ActionLister can be added to any type of Java GUI component.

    • 7). Create an actionPerformed() method that takes in an ActionEvent type as an argument.

      An example is: public void actionPerformed(ActionEvent e) { System.out.println("Go");}

      This code will make the computer print out "Go" when the button is pressed. Any action can be performed when an event occurs by placing the code implementation between the curly braces.

    • 8). Compile the code, and run the GUI.



Leave a reply