001package headfirst.observer.Swing; 002 003import java.awt.BorderLayout; 004import java.awt.event.ActionEvent; 005import java.awt.event.ActionListener; 006 007import javax.swing.JButton; 008import javax.swing.JFrame; 009 010public class SwingObserverExample { 011 JFrame frame; 012 013 public static void main(String[] args) { 014 SwingObserverExample example = new SwingObserverExample(); 015 example.go(); 016 } 017 018 public void go() { 019 frame = new JFrame(); 020 021 JButton button = new JButton("Should I do it?"); 022 button.addActionListener(new AngelListener()); 023 button.addActionListener(new DevilListener()); 024 frame.getContentPane().add(BorderLayout.CENTER, button); 025 026 // Set frame properties 027 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 028 frame.getContentPane().add(BorderLayout.CENTER, button); 029 frame.setSize(300,300); 030 frame.setVisible(true); 031 } 032 033 class AngelListener implements ActionListener { 034 public void actionPerformed(ActionEvent event) { 035 System.out.println("Don't do it, you might regret it!"); 036 } 037 } 038 039 class DevilListener implements ActionListener { 040 public void actionPerformed(ActionEvent event) { 041 System.out.println("Come on, do it!"); 042 } 043 } 044}