简体   繁体   English

Java Swing和JComboBox事件

[英]Java Swing and JComboBox Events

I have a JComboBox with multiple values in it. 我有一个JComboBox有多个值。 I need to be able to detect when the user clicks the JComboBox but does not change the currently selected item. 我需要能够检测用户何时单击JComboBox但不更改当前选定的项目。

Neither itemStateChanged nor actionPerformed fire when this happens. 发生这种情况时, itemStateChangedactionPerformed都不会触发。

What event should I be using? 我应该使用什么事件?

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? 如何在按下鼠标按钮时记录组合框的状态,并将其与释放鼠标按钮时盒子的值进行比较?

At this point, it's a simple equality check. 在这一点上,这是一个简单的相等检查。

Add a MouseListener to the JComboBox using its addMouseListener method. 使用addMouseListener方法将MouseListener添加到JComboBox You will want to extend MouseAdapter and override only the mouseClicked method. 您将需要扩展MouseAdapter并仅覆盖mouseClicked方法。

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. 我会使用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. 何时关闭,您将比较所选索引以查看它已更改。

I was looking specifically at right mouse click on items, so it's a slightly different problem. 我特意看右键点击项目,所以这是一个稍微不同的问题。 But the solution for me was to 但我的解决方案是

  1. Subclass JComboBox substituting getCellRenderer( ) with a subclassed DefaultListCellRenderer . 子类JComboBox用子类DefaultListCellRenderer替换getCellRenderer( )。

  2. In the cell renderer intercept getListCellRendererComponent() which has boolean isSelected , boolean cellHasFocus parameters and can be used to watch for mouse events and do list.setToolTipText() . 在单元格渲染器中拦截getListCellRendererComponent() ,它具有boolean isSelectedboolean cellHasFocus参数,可用于监视鼠标事件并执行list.setToolTipText()

I'm sure the non-final selection change will get there, where it can be intercepted. 我确信非最终选择更改将会到达那里,它可以被截获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM