I'd like to create a readonly combobox. The user should not be able to select another item from the popup list. That means that the popup list should not open or should be empty.
I see the following solutions:
Set a ComboBox model with only one item (the current selected item) so when the user clicks on the arrow button, an empty list is presented.
Add a
PopupMenuListener
and in thepopupMenuWillBecomeVisible
hide the menu. This is problematic: We have to callcombo.hidePopup();
from within aSwingUtilities.invokeLater()
The empty model approach seems a little bit clunky. The second approach shows the popup list for a fraction of a second, short enough to be noticed. This is very ugly.
Is there a third solution?
EDIT: Implemented solution:
I implemented the suggested method from splungebob and here is my code for future reference:
private void makeComboReadonly() {
Component editorComponent = box.getEditor().getEditorComponent();
if (editorComponent instanceof JTextField) {
((JTextField) editorComponent).setEditable(false);
}
for (Component childComponent : box.getComponents()) {
if (childComponent instanceof AbstractButton) {
childComponent.setEnabled(false);
final MouseListener[] listeners = childComponent.getListeners(MouseListener.class);
for (MouseListener listener : listeners) {
childComponent.removeMouseListener(listener);
}
}
}
final MouseListener[] mouseListeners = box.getListeners(MouseListener.class);
for (MouseListener listener : mouseListeners) {
box.removeMouseListener(listener);
}
final KeyListener[] keyListeners = box.getListeners(KeyListener.class);
for (KeyListener keyListener : keyListeners) {
box.removeKeyListener(keyListener);
}
box.setFocusable(false);
//box.getActionMap().clear(); //no effect
//box.getInputMap().clear();
}
The only problem is the Key-Event Alt-Down which oppens the popup menu even if I remove all the key listeners and clear the action map. I circumvent this problem by making the combo non focusable. Not ideal but good enough (-:
JLabel
or a not editableJTextField
. I thought you'd want aJComboBox
where the other options are visible, but you can't change the one selected even if you click on another item of the list. – Sherasherar