import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class RadioButtonTest extends JFrame {
    // name of the animals
    static String birdString = "Bird";
    static String catString = "Cat";
    static String dogString = "Dog";
    static String rabbitString = "Rabbit";
    static String pigString = "Pig";
    // picture to display the animal pictures
    JLabel picture = new JLabel();
    
    public RadioButtonTest() {
        // instantiate radio buttons
	JRadioButton birdButton = new JRadioButton(birdString);
        JRadioButton catButton = new JRadioButton(catString);
        JRadioButton dogButton = new JRadioButton(dogString);
        JRadioButton rabbitButton = new JRadioButton(rabbitString);
        JRadioButton pigButton = new JRadioButton(pigString);
	
	//add the buttons to a group
	ButtonGroup group = new ButtonGroup();
	group.add(birdButton);
	group.add(catButton);
	group.add(dogButton);
	group.add(rabbitButton);
	group.add(pigButton);
        
	// select the bird as the first picture
	birdButton.setSelected(true);
	picture.setIcon(new ImageIcon(birdString + ".gif"));
	
	// add radio buttons to a panel
	JPanel animalPanel = new JPanel(new GridLayout(0,1));
	animalPanel.add(birdButton);
	animalPanel.add(catButton);
	animalPanel.add(dogButton);
	animalPanel.add(rabbitButton);
	animalPanel.add(pigButton);

	// add animalPanel and picture to the JFrame
	getContentPane().add(animalPanel, BorderLayout.WEST); 
	getContentPane().add(picture); // add to the center
	
	// Register a listener for the radio buttons.
        AnimalListener myListener = new AnimalListener();
        birdButton.addActionListener(myListener);
        catButton.addActionListener(myListener);
        dogButton.addActionListener(myListener);
        rabbitButton.addActionListener(myListener);
        pigButton.addActionListener(myListener);
    }
    
    // inner class
    // we define a class inside another class
    // the class has access to all the members 
    class AnimalListener implements ActionListener { 
        public void actionPerformed(ActionEvent e) {
	    // set the picture
	    // the inner class can access the private member : picture
            picture.setIcon(new ImageIcon(e.getActionCommand()+".gif"));
        }
    }
    
    public static void main(String[] args) {
        RadioButtonTest f = new RadioButtonTest();
	f.setTitle("Animals");
	f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	f.pack();
	f.setVisible(true);
    }
}


	

 





    
