Derive a class from a component and implement an action listener inside the class. : Swing Action « Event « Java






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

   
  








Related examples in the same category

1.You can change event behavior dynamicallyYou can change event behavior dynamically
2.Keymap and KeyStroke DemoKeymap and KeyStroke Demo
3.Use Action classUse Action class
4.How to have multiple listeners
5.Demonstrate a listener being reusedDemonstrate a listener being reused