import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class EventHandlingDemo extends JFrame {
private JButton btnOk, btnCancel, btnExit, btnAction0, btnAction1;
public EventHandlingDemo() {
super("EventHandlingDemo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
final ActionListener listener = new ActionHandler();
c.add((btnOk = new JButton("btnOk") {
{
addActionListener(listener);
}
}));
c.add((btnCancel = new JButton("btnCancel") {
{
addActionListener(listener);
}
}));
c.add((btnExit = new JButton("btnExit") {
{
addActionListener(listener);
}
}));
c.add((btnAction0 = new JButton("btnAction0") {
{
addActionListener(listener);
}
}));
c.add((btnAction1 = new JButton("btnAction1") {
{
addActionListener(listener);
}
}));
pack();
setVisible(true);
}
public static void main(String[] args) {
new EventHandlingDemo();
}
class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == btnOk){
JOptionPane.showMessageDialog((Component)o,"btnOk was pressed!");
}else if(o == btnCancel){
JOptionPane.showMessageDialog((Component)o,"btnCancel was pressed!");
}else if(o == btnExit){
JOptionPane.showMessageDialog((Component)o,"btnExit was pressed!");
}else if(o == btnAction0){
JOptionPane.showMessageDialog((Component)o,"btnAction0 was pressed!");
}else if(o == btnAction1){
JOptionPane.showMessageDialog((Component)o,"btnAction1 was pressed!");
}
}
}
}