import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MyFrame extends JFrame
{
	/** 
	    Initializes this frame by adding components and associating
	    event handlers with these components.
	*/
	public MyFrame()
	{
		super("My Frame");
		this.setSize(500, 300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Store a label "to the north".  The variable
    // 'label' must be final since it is accessed
    // from within the inner classes below.
    final JLabel label = new JLabel("Press a button");
    this.add(label, BorderLayout.NORTH);
    
    // Initalize outer panel (container)
    JPanel outerPanel = new JPanel();
    outerPanel.setLayout(new GridLayout(3,3));

    // Construct an event handler for the first eight
    // buttons  
    class FirstActionListener implements ActionListener
    {
    	public void actionPerformed(ActionEvent e)
    	{
    		// Who caused the event?  (This will fail at
    		// runtime if e.getSource() is not a JButton.) 
    		JButton b = (JButton) e.getSource();
    		 
				// Show the text of the button that was pressed on
				// the label
				label.setText("You pressed: " + b.getText());     		
    	}
    } 

    ActionListener handler = new FirstActionListener();

    // Construct and add first eight buttons.  Associate an
    // event handler with these.
    JButton b;

    for (int i = 1; i <= 8; i++)
    {
    	b = new JButton("" + i); // "1", "2", ...
    	b.addActionListener(handler);
    	outerPanel.add(b);
    }
    
    // Construct inner panel (container)
		JPanel innerPanel = new JPanel();
    innerPanel.setLayout(new GridLayout(1, 2));

		class LeftActionListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				label.setHorizontalAlignment(SwingConstants.LEFT);
			}
		}

		class RightActionListener implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				label.setHorizontalAlignment(SwingConstants.RIGHT);
			}
		}
		
		b = new JButton("Left"); 
		b.addActionListener(new LeftActionListener());
    innerPanel.add(b);

		b = new JButton("Right"); 
		b.addActionListener(new RightActionListener());
    innerPanel.add(b);

    // add inner panel to outer panel
    outerPanel.add(innerPanel);
    
    // add outer panel to window
		add(outerPanel);
	}

  public static void main(String[] args)
  {
  	// Construct a frame. (Why is the following line
  	// legal?  Why can we store a MyFrame in a
  	// variable that should contain a JFrame?)
  	JFrame frame = new MyFrame();

    // Show the frame
  	frame.setVisible(true);
  }	
}
