Java Swing 和 JComboBox 事件
我有一个 JComboBox
,其中包含多个值。我需要能够检测用户何时单击 JComboBox
但不更改当前选定的项目。
发生这种情况时,itemStateChanged
和 actionPerformed
都不会触发。
我应该使用什么事件?
I have a JComboBox
with multiple values in it. I need to be able to detect when the user clicks the JComboBox
but does not change the currently selected item.
Neither itemStateChanged
nor actionPerformed
fire when this happens.
What event should I be using?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
按下鼠标按钮时记录组合框的状态,并将其与释放鼠标按钮时组合框的值进行比较怎么样?
MouseListener
< /a> 到JComboBox
mousePressed()
方法 将框的状态记录到临时变量mouseReleased()< /code> 方法
将框的值与临时变量的值进行比较
此时,这是一个简单的相等检查。
How about recording the combo box's state when the mouse button is pressed, and comparing it to the value the box has when the mouse button is released?
MouseListener
to theJComboBox
mousePressed()
method to record the box's state to a temp variablemouseReleased()
method to compare the box's value to the temp variable's valueAt this point, it's a simple equality check.
使用
addMouseListener
方法将MouseListener
添加到JComboBox
中。您将需要扩展MouseAdapter
并仅重写mouseClicked
方法。Add a
MouseListener
to theJComboBox
using itsaddMouseListener
method. You will want to extendMouseAdapter
and override only themouseClicked
method.如果用户使用键盘打开弹出窗口,然后使用退出键关闭弹出窗口怎么办?
我会使用 PopupMenuListener。这应该处理鼠标和键盘操作。这个概念与其他建议相同。当显示弹出窗口时,您可以保存选定的索引。当关闭时,您可以比较所选索引以查看它是否已更改。
What if the user users the keyboard to open the popup and then uses the escape key to close the popup?
I would use a PopupMenuListener. This should handle both mouse and keyboard actions. The concept would be the same as other suggestions. When the popup is displayed you save the selected index. When is closes you compare the selected index to see it it has changed.
我专门研究了鼠标右键单击项目,所以这是一个略有不同的问题。
但对我来说,解决方案是
子类
JComboBox
用子类DefaultListCellRenderer
替换getCellRenderer(
)。在单元格渲染器中拦截
getListCellRendererComponent()
,它具有boolean isSelected
、boolean cellHasFocus
参数,可用于监视鼠标事件和dolist.setToolTipText()
.我确信非最终选择更改将到达那里,在那里它可以被拦截。
I was looking specifically at right mouse click on items, so it's a slightly different problem.
But the solution for me was to
Subclass
JComboBox
substitutinggetCellRenderer(
) with a subclassedDefaultListCellRenderer
.In the cell renderer intercept
getListCellRendererComponent()
which hasboolean isSelected
,boolean cellHasFocus
parameters and can be used to watch for mouse events and dolist.setToolTipText()
.I'm sure the non-final selection change will get there, where it can be intercepted.