2

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 ]
mKorbel
  • 109,525
  • 20
  • 134
  • 319
sdasdadas
  • 23,917
  • 20
  • 63
  • 148
  • 2
    *"I would like for the ComboBox to expand horizontally"* Sounds horrid. 1) It would be very crowded horizontally. 2) I can 'page down' or 'page up' through a vertically arranged combo box with many entries, but what is the button for paging 'right' or 'left'? – Andrew Thompson Oct 12 '12 at 18:39
  • @AndrewThompson, I initially wrote a comment defending my design choices - but I realized that it's of little use when I'm the only one who can see the interface. This is just a technical question. :) – sdasdadas Oct 12 '12 at 18:43
  • I don't think you will be able to find solution with this standard JCompoBox. I recommand you instead to implement your own JComponent –  Oct 12 '12 at 18:44

1 Answers1

1

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());

Nick Rippe
  • 6,465
  • 14
  • 30
  • @mKorbel - I wasn't sure if there was anything special that Metal was doing which Basic didn't have (and suspected there was with more advanced UI like Nimbus), so I went with Metal. Was this a valid concern, or is the consensus just to use Basic? – Nick Rippe Oct 12 '12 at 19:07
  • 1
    enable horizontal JScrollBar, disable vertical (xxx_NEVER) set orientation for JList, pack() – mKorbel Oct 12 '12 at 19:23
  • I am overriding the BasicComboBoxUI and it seems to be working - I'll post my code here when I'm finished. Thank you both. – sdasdadas Oct 12 '12 at 20:00
  • @sdasdadas [here is rest that you'll need](http://stackoverflow.com/a/11435850/714968), I woudn't be to override BasicXxxUI – mKorbel Oct 12 '12 at 21:15
  • @NickRippe BasicXXXUI is usually the root class of all UI of all other "regular" L&F in Java. Metal is specific to the "Metal" L&F, and I am guessing there is an AquaComboxBoxUI, a WindowsComboBoxUI and a SynthComboBoxUI. So if you don't know which L&F is running, the most "general" parent classe is usually BasicXXXUI, in this case BasicComboBoxUI. – Guillaume Polet Oct 12 '12 at 21:56