Last active
December 14, 2015 16:48
-
-
Save raineorshine/5117436 to your computer and use it in GitHub Desktop.
Demonstrates how to hook up a function to the 'click' event of a button with addActionListener in a Swing-based Java application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment