Mega Code Archive

 
Categories / Java / Event
 

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);   } }