问题描述
我读到一个 JButton
实现 ItemSelectable
,并在文档中具有方法 addItemListener
所以我可以认为它可以生成一个 ItemEvent
...但是当我注册一个 JButton
JMenuItem )接口的事件没有增加?
为什么? p>
我知道如果在文档中报告一个组件有一个添加....侦听器,这意味着它支持该事件...但是经验并不常见...
真相如何?
一个按钮被按下(触发 ActionEvent
)和一个按钮被选择(触发 ItemEvent
)。默认情况下,一个 JButton
由$ code> javax.swing.DefaultButtonModel 支持。如果您在默认按钮模型中查看 setPressed
和 setSelected
方法,您将看到触发不同事件的代码
所以如果你以编程方式调用 JButton.setSelected
,你的项目监听器将被触发。如果您点击按钮,您将只会收到该操作事件。
另请注意,使用 JButton
不像说,一个 JToggleButton
),你可能不会在视觉上看到很多选择。
I read that a JButton
implements ItemSelectable
and into documentation it has the method addItemListener
so I can argue that it can generate an ItemEvent
... but when I register with a JButton
(but also for a JMenuItem
) that interface the event is not rised?
Why?
I understand that if into docs is reported that a component has an add....Listener it means that it support that event... but for experience isn't often so...
What's the truth?
There is a difference between a button being "pressed" (which fires an ActionEvent
) and a button being "selected" (which fires the ItemEvent
). By default a JButton
is backed by a javax.swing.DefaultButtonModel
. If you look at the setPressed
and setSelected
methods in default button model you'll see the code that fires the different events.
So if you programmically call JButton.setSelected
, your item listener will be fired. If you click the button, you'll only get the action event.
Note also that with a JButton
(unlike, say, a JToggleButton
) you probably won't see much visually when it is selected.
这篇关于itemStateChanged on JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!