Java Swing issue, why is a changeEvent firing extra events with a jButton?

1.2k views Asked by At

While trying to learn JButton events I'm getting confused because of a problem. The sample code I'm using is here.

The code is below:

jb.addChangeListener(new ChangeListener() 
{
    @Override
    public void stateChanged(ChangeEvent e)
    {
        System.out.println("Changed");
    }
});

This is a demo application so only one button is used and it has the focus when the application is starting up. I simply press the spacebar to simulate a click event. As per the tutorial (by OReilly: Java Swing) it should fire the change event twice followed by an action event followed by action event. i.e.

  1. Changed
  2. Changed
  3. ActionEvent
  4. Changed

But after the 4th event I got another ChangeEvent. There is actually 5 events for a single click in the way mentioned above. If I'm trying to click with mouse the result is even more different. When the mouse entered into the button region, an event fired.

I don't know what change occurs and ChangeEvent is raised when the mouse hovers over the JButton. I don't find a similar method like getChangedState (ItemStageChanged) for JButton to know what state changed in that button. Since it's about learning, I don't want to use ActionListener unless I understand this issue.

So my questions are:

  1. Why do I see the ChangeEvent twice where it should be one?
  2. How do I find what state is changed in JButton?

Edit: I see there are 5 states mentioned in DefaultButtonModel and they are defined in ButtonModel interface. But JButton don't have fields,methods to get those states. did they get ignored willingly? Or JButton(and AbstractButton) don't relates with ButtonModel interface.

Edit 2: The tutorial indicates,

Depending on the L&F, there may also be additional ChangeEvents.

I'm using Swing's default L&F in Windows but I'm getting different results than tutorial's expectation.

1

There are 1 answers

0
Bobby On

The five events that happen when you press the button, in order are: ChangeEvent: Armed - true ChangeEvent: Pressed - true ActionEvent ChangeEvent: Pressed - false ChangeEvent: Armed - false

If you use your mouse to press the button then in addition to the above, there will be a ChangeEvent for Rollover: true when the mouse moves over the button and another for Rollever: false when the mouse moves away from the button.