raineorshine
3/8/2013 - 3:56 PM

Demonstrates how to hook up a function to the 'click' event of a button with addActionListener in a Swing-based Java application

Demonstrates how to hook up a function to the 'click' event of a button with addActionListener in a Swing-based Java application

package actionlistenerdemo;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
// The primary class is a JFrame which can be shown when the program starts
public class ActionListenerDemo extends JFrame {
    
    /*  main is just housed inside of the primary class. It creates a new 
        instance of the class to show the frame. 
    */
    public static void main(String[] args) {
        ActionListenerDemo demo = new ActionListenerDemo();
    }
    
    // In the constructor, add a button and show the frame
    public ActionListenerDemo()
    {
        JButton button = new JButton("You can click me.");
        add(button);
        
        /*  In order to handle the click even of the button, call
            addActionListener passing it an instance of the private class
            that implements ActionListener. 
        */
        button.addActionListener(new MyButtonListener());
        
        /*  This "hooks up" your event handler so that the actionPerformed
            method of the private class is called whenever the button is clicked.
            button.addActionListener(new ButtonListener()); 
        */
        setLayout(new FlowLayout());
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }
 
    /*  The listener class is declared as a private nested class so that it can
        only be used within the ActionListenerDemo class. It would also work
        if we declared it as a separate public class, it just wouldn't be as
        nicely encapsulated.
        
        "implements" means we are making a promise to add all of the functions
        that the interface requires. For an ActionListener this is simple: it
        just requires an actionPerformed function.
    */
    private class MyButtonListener implements ActionListener {
        
        /* This function will be called automatically on the click or action
            event of any component we add it to. 
        */
        public void actionPerformed(ActionEvent e){
            JOptionPane.showMessageDialog(null, "Good Click!");
        }
    }
}