Handling Change Events

Buttons fire action events when they’re clicked. Action listeners subscribe to the buttons they are interested in. When one is clicked the listener’s actionPerformed method is called with the action event that was created:

class ButtonListener implements ActionListener {
public ButtonListener(JButton someButton) {
someButton.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
    // respond
}
}

When selected, menu items also fire action events.

Unfortunately, sliders fire change events instead of action events and pass them to change listeners

class SliderListener implements ChangeListener {
   public SliderListener(JSlider someSlider) {
   someSlider.addChangeListener(this);
   }
   public void stateChanged(ChangeEvent ce) {
     // respond
   }
}

Chicken Tournament

In the movie Rebel Without a Cause James Dean challenges his rival to a game of chicken.

Rebel Without a Cause

In this game opponents drive toward each otherat top speed. At the last moment each must unilaterally decide to be a chicken and swerve away or be bold and continue straight. (Such games are often played out in business and international relations.)

Chicken Tournament is a customization of the SimStation framework. Mobile agents are called rebels and their world is a tournament:

A diagram of a game

AI-generated content may be incorrect.

Notice that Tournament has two static variables. SwerveTendency is the probability that a rebel will swerve and population is the initial number of rebels.

When updated, a rebel selects a random neighbor, plays one round of chicken with it, then moves. Both rebels choose to swerve or not using the following choose method:

boolean choose() {
   return Utilities.rng.nextInt(100) > Tournament.swerveTendency;
}

The static variables can be setusing sliders or from the edit menu:

A screenshot of a computer

AI-generated content may be incorrect.

The second slider is dynamic. When moved all rebels tend to become more or less chickenj. The first slider is only consulted when the simulation starts.

To make this a work I had to make the tournament panel a change listener:

A diagram of a slider

AI-generated content may be incorrect.

To make the menu items work I had to create command classes for setting the population and cheat tendency:

A diagram of a function

AI-generated content may be incorrect.

One issue is that if the user sets the swerve tendency using the menu, then the sliders should update themselves. I achieved this by overriding the AppPanel’s update method. Recall it subscribes to the model. To make this work I need to provide the Tournament with a setSwerveTendency method that calls changed.

Here’s my code: Tournament.java.