Action Event Handling in JAVA

Throughout AWT, and all Java APIs for that matter, event handling has been consistent:

  1. Implement a listener interface (such as java.awt.event.ActionListener)
  2. Provide an implementation of all listener interface methods (such as actionPerformed( ActionEvent e ))
  3. Add your class as a listener to a component, which generates events by calling its addXXXListener() method (such as calling javax.swing.JButton‘s addActionListener() method)

i will go through 3 methods to perform Action Event Handling in Java

First method:

1- create a Handler Class in a separate file that implements from ActionListener interface.

2- overwrite the abstract method actionPerformed of the ActionListener interface, with the code we want to be executed upon the action on our object.

3- create instance of the Handler class, and add it as an action listener on the object we want like button for example.

Example :

in the following example we will create a button from the swing library, and apply the action that when a user click the button, we will show a message dialog.

File Handler.class

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

import javax.swing.*;/**

*

* @author ahmedabdelaliem

*/

//we create the Handler class and implement from ActionListener interface

public class Handler implements ActionListener{

//now we overwrite the abstract method of ActionListener interface

public void actionPerformed (ActionEvent event){

// here goes the code we want to execute when the action happen, for example show a message dialog with the below text

JOptionPane.showMessageDialog(null, "You Have just clicked the button");

}

}

file ButtonTest.java

/** *

* @author ahmedabdelaliem

*/

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

import java.awt.*;

import javax.swing.*;// we create our class and inherit from JFrame to create our GUI

public class ButtonTest extends JFrame{

// we create an empty reference with JButton type

private JButton plainButton,;

// we create the constructor of the class

public ButtonTest(){

//set up the container

Container con = getContentPane();

con.setLayout(new FlowLayout());

// create an object of the JButton

plainButton = new JButton();

plainButton.setText("Regular Button"); // set the text on the button

//create an object of our Handler

Handler h = new Handler();

// now we add the Handler object we created as Action Listener for the button

plainButton.addActionListener(h);

//now we add the button to the container and show the frame.

con.add(plainButton);

setSize(400,300);

setVisible(true);

}

}

file Main.java

/** *

* @author ahmedabdelaliem

*/

public class Main {

public static void main(String[] args) {

// we create an object of our ButtonTest Class

ButtonTest b1 = new ButtonTest();

b1.setDefaultCloseOperation(b1.EXIT_ON_CLOSE);    }

}

now the output of this simple application : a frame will show with a button on it, and when we click the button a message dialog will appear.

the disadvantage of this method is that we need to create a separate handler for each object we want a handler for,

for example if we have a form with 10 buttons with different actions when clicked, then we need to create 10 Handlers in 10 files with 10 different actions

that doesn’t make sense at all.

so this is why we follow one of the next 2 methods,

Method 2 : create the Handler class as inner class of our class to handle the actions on the components in our class

Example :

File : CheckButtonTest.java

import javax.swing.*;import java.awt.*;

import java.awt.event.*;

/**

*

* @author ahmedabdelaliem

*/

public class CheckBoxTest extends JFrame{

JCheckBox b1,b2; // we create 2 referneces with JCheckBox type

JTextField t1; // we create 1 reference with JTextField type    // we create the constructor of the class

public CheckBoxTest() {

//we call the constructor of our super class and give it the title of the frame

super ("Check Box Test");

//now we setup the container

Container con = getContentPane();

con.setLayout(new FlowLayout());

// we create the text field object with pre entered text

t1 = new JTextField("This is the test text");

// we set the font for the text field

t1.setFont( new Font("serif", Font.PLAIN, 14));

// now we add the text box to the container

con.add(t1);

// we create object for the checkbox and give it Bold value

b1 = new JCheckBox("Bold");

//we add the checkbox to the container

con.add(b1);

// we create another object for the second box and give it italic value

b2 = new JCheckBox("Italic");

// we add the checkbox to the container

con.add(b2);

// now we create the handler object

Handler h = new Handler();

// we add the handler as item listener for the 2 checkboxes

b1.addItemListener(h);

b2.addItemListener(h);

// now we view the frame

setSize(400,300);

setVisible(true);

}

// here we create the handler class   as inner class

private class Handler implements ItemListener{

private int bold = Font.PLAIN; // we setup initial values for the bold, italic variables

private int italic = Font.PLAIN;

// we overwrite the abstract method of the ItemListener interface

public void itemStateChanged(ItemEvent event){

if (event.getSource() == b1){ // here we check which checkbox is checked

if (event.getStateChange() == event.SELECTED){ // here we check if it is selected or the selection is removed

bold = Font.BOLD; // if conditions apply, we set the bold variable as BOLD

//t1.set;

}else{

bold = Font.PLAIN;

}

}else if (event.getSource() == b2){

if (event.getStateChange() == event.SELECTED){

italic = Font.ITALIC;

}else{

italic = Font.PLAIN;

}

}

// here we add the 2 variables and apply the format to our font

t1.setFont(new Font("Serif", bold + italic, 14));

}

}

}

File : Main.java

/**

 *

 * @author ahmedabdelaliem

 */

public class Main {    /**

     * @param args the command line arguments

     */

        // TODO code application logic here

        public static void main(String[] args) {

        // TODO code application logic here

       CheckBoxTest checkBox = new CheckBoxTest();

       checkBox.setDefaultCloseOperation(CheckBoxTest.EXIT_ON_CLOSE);

    }

}

This method is better than the first one, cause it allow us to create one handler for many objects and the handler can reach and compare the variables of our main class.

The third method is to create an instance of

Leave a Reply

avatar
  Subscribe  
Notify of