检测JRadioButton状态更改 [英] Detecting a JRadioButton state change

查看:854
本文介绍了检测JRadioButton状态更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在用鼠标单击时检测JRadioButton何时从未选定更改为选定?我已尝试在按钮上使用ActionListener,但每次点击单选按钮时都会触发,而不是仅在将状态更改为已选择时触发。

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'.

我'想到维护一个布尔变量来记住按钮的状态,并在ActionListener中测试它以查看是否要更改其状态,但我想知道是否有更好或更清洁的解决方案。

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.

推荐答案

看看JRadioButton。 addItemListener ()

Look at JRadioButton.addItemListener()

编辑:你不太可能想要使用changeListener,因为它每次点击多次触发。每次单击时,itemListener仅触发一次。
见这里

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:为了扩展这一点,每次用户点击它时,jradioButton上的actionListener都会触发,即使它已被选中。如果那就是你想要的,那很好,但我觉得很烦人。我只想通知它被选中或取消选择。

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.

ChangeListener将触发所有类型的事情,这意味着你的监听器每次点击将收到5个或更多事件。不好。

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

如果所选或取消选择的状态发生变化,则itemlistener将仅激活 。这意味着用户可以多次单击它,如果它没有改变则不会触发。在你的处理程序方法中,你必须有一个 if 块检查 SELECTED DESELECTED status并在那里做任何事情:

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.

这篇关于检测JRadioButton状态更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆