Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

java - Detecting a JRadioButton state change

How can I detect when a JRadioButton is changed from 'unselected' to 'selected' when clicked with the mouse? I've tried using an ActionListener on the button, but that gets fired every time the radiobutton is clicked, not just when it's changing state to 'selected'.

I've thought of maintaining a boolean variable that remembers the state of the button, and test it inside the ActionListener to see whether to change its state but I'm wondering if there's a much better or cleaner solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Look at JRadioButton.addItemListener()

EDIT: It is unlikely you want to use a changeListener as it fires multiple times per click. An itemListener fires only once per click. See here

EDIT2: Just to expand on this, an actionListener on a jradioButton will fire every time a user clicks on it, even if it is already selected. if that's what you want, fine, but I find it annoying. I only want to be notified it it is selected or deselected.

A ChangeListener will fire for all sorts of things, meaning your listener will receive 5 or more events per click. Not good.

An itemlistener will fire only if the selected or deselected state changes. This means that a user can click on it multiple times and it will not fire if it doesn't change. In your handler method you will have to have an if block checking for SELECTED or DESELECTED status and do whatever there:

@Override
public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
        // Your selected code here.
    }
    else if (e.getStateChange() == ItemEvent.DESELECTED) {
        // Your deselected code here.
    }
}

It just works better because you know that if you are in the method then the radio button has either just been selected or deselected, not that the user is just banging on the interface for some unknown reason.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...