Using an inner ActionListener class.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InnerClass {
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public InnerClass() {
JButton close = new JButton("Close");
ButtonListener listener = new ButtonListener();
close.addActionListener(listener);
JFrame f = new JFrame();
f.add(close);
f.setSize(300, 200);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args) {
new InnerClass();
}
}
Related examples in the same category