Derive a class from a component and implement an action listener inside the class.
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; class MyButton extends JButton implements ActionListener { public MyButton(String text) { super.setText(text); addActionListener(this); } public void actionPerformed(ActionEvent e) { System.exit(0); } } public class UsingInterface { public static void main(String[] args) { MyButton close = new MyButton("Close"); JFrame f = new JFrame(); f.add(close); f.setSize(300, 200); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }
1. | You can change event behavior dynamically | ||
2. | Keymap and KeyStroke Demo | ||
3. | Use Action class | ||
4. | How to have multiple listeners | ||
5. | Demonstrate a listener being reused |