Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JCombobox look like a JTextField

Tags:

java

swing

Is there a good(and easy) way to make a JCombobox look like a JTextField? By this I mean there should not be a dropdown button, but when the user enters something it should show multible results.

Basically the same way google, youtube, facebook etc. works.

like image 564
Mads Andersen Avatar asked May 04 '09 22:05

Mads Andersen


1 Answers

JComboBox comboBox = new JComboBox();
comboBox.setUI(new BasicComboBoxUI() {
    @Override
    protected JButton createArrowButton() {
        return new JButton() {
            @Override
            public int getWidth() {
                return 0;
            }
        };
    }
});

Making getWidth() return 0 ensures that:
a) the button is not shown
b) no space is reserved for it, letting you type in the whole field

I found that I had to do invoke .setUI() via SwingUtilities.invokeLater(), but depending on the structure of your code, you might not have to.

If you want autocomplete, add some items to the combo box, and use AutoCompleteDecorator.decorate(comboBox). The AutoCompleteDecorator class is part of SwingX, as previously mentioned.

This might make your box look weird when using another L&F, so you will have to choose which CombiBoxUI to instantiate, to get the right look.

If you do not want the drop-down to appear when there is nothing in the combo box, override this method in the BasicComboBoxUI as well:

@Override
public void setPopupVisible(JComboBox c, boolean v) {
    // keeps the popup from coming down if there's nothing in the combo box
    if (c.getItemCount() > 0) {
        super.setPopupVisible(c, v);
    }
}
like image 176
Markus Jevring Avatar answered Nov 03 '22 08:11

Markus Jevring