Code:
/** * File: jbuttonAddEvent.java * Tiltle: Add Event Listener on JButton * Author: http://java-program-sample.blogspot.com/ */ //Java Core Package import javax.swing.*; //Java Extension Package import java.awt.*; import java.awt.event.*; public class jbuttonAddEvent extends JFrame { //Initializing JButton private JButton button; //Setting up GUI public jbuttonAddEvent() { //Setting up the Title of the Window super("Add Event Listener on JButton"); //Set Size of the Window (WIDTH, LENGTH) setSize(300,100); //Exit Property of the Window setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Constructing JButton button = new JButton("Click Me for my First Event"); //Setting up the container ready for the components to be added. Container pane = getContentPane(); setContentPane(pane); //Setting up the container layout FlowLayout flow = new FlowLayout(FlowLayout.CENTER); pane.setLayout(flow); //Implemeting Even-Listener on JButton using ActionListener button.addActionListener( new ActionListener() { //Handle JButton event if Enter key is pressed or if mouse is clicked. public void actionPerformed(ActionEvent event) { //Message to be displayed after the button is pressed or clicked. String message = "Event Listener Successfully Implemented"; //Display the message using JOptionPane if the Event is successfully implemented. JOptionPane.showMessageDialog(null, message,"Event",JOptionPane.INFORMATION_MESSAGE); } } ); //Adding the JButton component to the container pane.add(button); /**Set all the Components Visible. * If it is set to "false", the components in the container will not be visible. */ setVisible(true); } //Main Method public static void main (String[] args) { jbuttonAddEvent jbe = new jbuttonAddEvent(); } }
Important Part of the Program:
//Implemeting Even-Listener on JButton using ActionListener button.addActionListener( new ActionListener() { //Handle JButton event if Enter key is pressed or if mouse is clicked. public void actionPerformed(ActionEvent event) { //Message to be displayed after the button is pressed or clicked. String message = "Event Listener Successfully Implemented"; //Display the message using JOptionPane if the Event is successfully implemented. JOptionPane.showMessageDialog(null, message,"Event",JOptionPane.INFORMATION_MESSAGE); } } );