/*
 * file: FocusDemo.java
 * 
 * This demo shows JButton components 
 * that publish FocusEvent and ActionEvent
 * Note that the focus events are handled
 * prior to the action events
 * 
 * JTextField components publish ActionEvent
 * with carriage return
 * 
 * Use tab (or whatever the platform supports) 
 * to move focus bewteen the components
 */
 
import java.awt.event.FocusListener; 
import java.awt.event.ActionListener; 
import java.awt.event.FocusEvent;
import java.awt.event.ActionEvent;
import javax.swing.*; 
import java.awt.FlowLayout;

public class FocusDemo extends JFrame implements FocusListener,ActionListener {
    String newline; 
	JButton jb1; 
	JButton jb2; 
	JTextField tf1;
	
	FocusDemo() { 
		super("Focus Demo");
		newline = System.getProperty("line.separator");
		jb1 = new JButton("Button 1"); 
		jb2 = new JButton("Button 2");
		tf1 = new JTextField(20);
		
		//Use FlowLayout for the JFrame
		getContentPane().setLayout(new FlowLayout());
		
		// register the buttons and text field as publishers
		// "this" class as the subscriber
		jb1.addFocusListener(this);
		jb1.addActionListener(this);
		jb2.addFocusListener(this);
		jb2.addActionListener(this);
		tf1.addFocusListener(this);
		tf1.addActionListener(this);
		
		// add the components 
		getContentPane().add(jb1); 
		getContentPane().add(jb2); 
		getContentPane().add(tf1); 
		
		// show the frame
		setSize(300,150); 
		setVisible(true);
	}//Constructor
	
	public void focusGained(FocusEvent e) {
     	displayMessage("Focus gained", e);
 	}

	public void focusLost(FocusEvent e) {
 		displayMessage("Focus lost", e);
    	}

    	void displayMessage(String prefix, FocusEvent fe) {
		System.out.println(prefix
                    	+ ": "
                  	+ fe.getComponent().getClass()
                        + newline); 
    	}//displayMessage
	
	
	public void actionPerformed(ActionEvent ae) { 
		System.out.println("actionPerformed method" + newline);
	}
	
	public static void main(String args[]) { 
		new FocusDemo();
	}
	
} //FocusDemo
