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?
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 the JComboBox
mousePressed()
method to record the box's state to a temp variable mouseReleased()
method to compare the box's value to the temp variable's value At this point, it's a simple equality check.
Add a MouseListener
to the JComboBox
using its addMouseListener
method. You will want to extend MouseAdapter
and override only the mouseClicked
method.
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.
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
substituting getCellRenderer(
) with a subclassed DefaultListCellRenderer
.
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()
.
I'm sure the non-final selection change will get there, where it can be intercepted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.