Java GUIs - ActionListeners & Lambdas

Thomas J Kennedy

Contents:

There are two ways to add a Listener to a GUI component (e.g., a JButton or a JTextField). We have focused primarily on the Java ActionListener.

Consider the following code snippet.


import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * A GUI Program that extends the JFrame class * to generate a Window. */ public class ButtonExample extends JFrame { /** * Control - start generation */ private JButton clickButton; /** * Constructor */ public ButtonExample() { // Invoke the JFrame (base class) constructor super("Button Example"); // Set action for upper right close button setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container cp = getContentPane(); // Create a button clickButton = new JButton("Click Me!"); /* ...Add click button Listener... */ // Setup and add to the Main Container cp.setLayout(new BorderLayout()); cp.add(clickButton, BorderLayout.CENTER); // Package Everything pack(); setLocationRelativeTo(null); } /** * Generate a message (pop-up dialog window). */ void displayMessage() { JOptionPane.showMessageDialog(null, "The Game", "The Game", JOptionPane.ERROR_MESSAGE); } /** * Main function */ public static void main(String[] args) { new ButtonExample().setVisible(true); } }

If one wanted to bind displayMessage to the button, clickButton, an ActionListener would be the default choice.

1 Using An ActionListener

Let us use an immediate class.

2 Using A Lambda Function

Let us use a lambda function.