import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AnimalTypeRx extends JFrame implements ActionListener,
ItemListener
{
private JRadioButton cat;
private JRadioButton dog;
private JRadioButton bird;
private JComboBox Zoo;
private String[] catNames =
{
"Tom", "Meow", "Pete"
};
private String[] dogNames =
{
"bobby", "Roy", "Lassie"
};
private String[] birdNames =
{
"kiko", "tweety", "birdy"
};
private DefaultComboBoxModel cmb;
public AnimalTypeRx()
{
super("zoo!");
setLayout( new FlowLayout() );
cat = new JRadioButton("cat",true);
dog = new JRadioButton("dog",false);
bird = new JRadioButton("bird",false);
ButtonGroup animals = new ButtonGroup();
animals.add(cat);
animals.add(dog);
animals.add(bird);
add(cat);
add(dog);
add(bird);
cmb = new DefaultComboBoxModel(catNames);
Zoo = new JComboBox(cmb);
Dimension d = Zoo.getPreferredSize();
System.out.printf("d = [%d, %d]%n", d.width, d.height);
d.width = 85;
Zoo.setPreferredSize(d);
add(Zoo);
// Zoo.addActionListener(this);
// This is all we need.
cat.addActionListener(this);
dog.addActionListener(this);
bird.addActionListener(this);
// Just to see what this can do.
cat.addItemListener(this);
dog.addItemListener(this);
bird.addItemListener(this);
}
public void actionPerformed(ActionEvent evt)
{
JRadioButton rb = (JRadioButton)evt.getSource();
String[] items = null;
if(rb == cat)
items = catNames;
if(rb == dog)
items = dogNames;
if(rb == bird)
items = birdNames;
resetModelData(items);
}
private void resetModelData(String[] items)
{
cmb.removeAllElements();
// The view component listens to the model and
// updates itself when changes are made to the model.
for(int i = 0; i < items.length; i++)
{
cmb.addElement(items[i]);
}
}
public void itemStateChanged(ItemEvent evt)
{
if(evt.getStateChange() == ItemEvent.SELECTED)
{
JRadioButton rb = (JRadioButton)evt.getSource();
if (rb == cat)
{
System.out.println("cat selected");
}
else if (rb == dog)
{
System.out.println("dog selected");
}
else if (rb == bird)
{
System.out.println("bird selected");
}
}
}
public static void main(String[] args)
{
AnimalTypeRx test = new AnimalTypeRx();
test.setDefaultCloseOperation(EXIT_ON_CLOSE);
test.setSize(400,400);
test.setVisible(true);
}
}