user235236 user235236 - 4 months ago 28
Java Question

JComboBox mouseClicked on cell

I am trying to call a function when a user clicks (with the mouse) on an item in a JComboBox; however, I don't want this event fired for any keyboard events - I only want this fired for a click on a particular cell of the dropdown (I know about addActionListener and addItemListener, but these are fired for more events than I want).

EDIT: I should have specified that mouseClicked doesn't work either - no events seem to be fired (however, they were at one point but when that happened, they fired for clicks on the text field as well), but I thought that was assumed from the title.

I have also tried the solution given here (also doesn't work): Editable JCombobox mouseclicked event not working

EDIT2: I tried the following, but still no output on click:

try {
Field popupInBasicComboBoxUI = BasicComboBoxUI.class.getDeclaredField("popup");
popupInBasicComboBoxUI.setAccessible(true);
BasicComboPopup popup = (BasicComboPopup)popupInBasicComboBoxUI.get(attachedCB.getUI());

Field scrollerInBasicComboPopup = BasicComboPopup.class.getDeclaredField("scroller");
scrollerInBasicComboPopup.setAccessible(true);
JScrollPane scroller = (JScrollPane)scrollerInBasicComboPopup.get(popup);

scroller.getViewport().getView().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("nope");
}
});
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}

Answer

You missed adding it to the scrollPane's viewport view in the link I posted in the comments.

Field scrollerInBasicComboPopup = BasicComboPopup.class.getDeclaredField("scroller");
scrollerInBasicComboPopup.setAccessible(true);
JScrollPane scroller = (JScrollPane) scrollerInBasicComboPopup.get(popup);
scroller.getViewport().getView().addMouseListener(listener);
Comments