more examples en
    
 

IMPLEMENTING AN ACTIONLISTENER USING AN ANONYMOUS LOCAL CLASS

API

javax.swing.JFrame
javax.swing.JButton
javax.swing.JLabel
java.awt.GridLayout
java.awt.event.ActionListener
java.awt.event.ActionEvent

 



Prior to Java 8, the only possibility to register an eventhandler was using an anonymous local class (a listener interface or an adapter class) and implementing the abstract methods of interest.

 

 1 package at.krux.javase.gui.event;

 2 import java.awt.GridLayout;
 3 import java.awt.event.ActionEvent;
 4 import java.awt.event.ActionListener;
 5 import javax.swing.JButton;
 6 import javax.swing.JFrame;
 7 import javax.swing.JLabel;

 8 public class ActionListenerAnonymousClass {
	
 9   JFrame frame;
10   JButton button;
11   JLabel label;
12   GridLayout grid = new GridLayout(2, 1);
	
13   ActionListenerAnonymousClass() {
14     this.frame = new JFrame();
15     this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16     this.button = new JButton("OK");
17     this.label = new JLabel("waiting for an ActionEvent to occur...", JLabel.CENTER);
18     this.frame.setLayout(grid);
		
19     this.button.addActionListener(new ActionListener() {
20       public void actionPerformed(ActionEvent e) {
21         label.setText("an ActionEvent has occurred!");
22       }			
23     });

24     this.frame.add(label);
25     this.frame.add(button);
26     this.frame.setBounds(200, 200, 450, 250);
		
27     this.frame.setVisible(true);
28   }

29   public static void main(String[] args) {
30     new ActionListenerAnonymousClass();
31   }
32 }