Search code examples
javaswingjscrollpanejcomboboxjpopup

How do I make my Swing JComboBox expand horizontally instead of vertically?


I am working with Swing and am adding a JComboBox to a JPanel. Normally, when you click a JComboBox it enumerates the possible options vertically (similar to combo boxes on any website).

However, I would like for the ComboBox to expand horizontally - is there any way to do this without writing a custom renderer?

Vertical Expansion

[ ComboBox ]

- Option
- Option
- Option

Horizontal Expansion

[ ComboBox ] -- [ Option | Option | Option | Option ]

Solution

  • I'm pretty sure the answer to your question is "no". You're going to have to build at least part of a renderer to do this for you. But here's a start:

    //Override the createPopup method - everything else can stay the same
    public static CustomRenderer extends MetalComboBoxUI{
        @Override
        protected ComboPopup createPopup() {
            // Do something different here
            ComboPopup result = super.createPopup();
            return result;
        }
    }
    

    And you will want to install this UI on the ComboBox you want it applied to using box.setUI(new CustomRenderer());