Search code examples
javaswingjcombobox

Hide the button of a JComboBox if is !enabled


I would like to extends JComboBox class no change something, I want the new component to hide the selection button when the combobox is disabled.

I can't find where this button is created

EDIT : so far I am using this code :

@Override
public void setEnabled(boolean b)
{
    super.setEnabled(b);

    Component[] comps = getComponents();
    for(Component comp : comps)
    {
        if(comp instanceof MetalComboBoxButton)
        {
            final MetalComboBoxButton dropDownButton = (MetalComboBoxButton) comp;
            dropDownButton.setVisible(b);
            break;
        }
    }
}

EDIT 2 : I was unable to do what I want finally, as if I switch to Nimbus PLAF, even if I hide the button the background is drawn, so only the arrow is hidded, everything else is still there.

I will have to do with a JPanel.


Solution

  • technically, you can subclass the JComboBox and either remove/add the button (as shown by @flash) or toggle its visibility

        final JComboBox box = new JComboBox(new Object[] {1, 2, 3}) {
    
            /** 
             * @inherited <p>
             */
            @Override
            public void setEnabled(boolean b) {
                if (b == isEnabled()) return;
                for (Component child : getComponents()) {
                    if (child instanceof JButton) {
                        child.setVisible(b);
                        break;
                    }
                }
                super.setEnabled(b);
            }
    
        };
    

    You might want to reconsider the requirement, though, because it is non-standard ui behaviour - and as such might confuse users