Search code examples
javafxcombobox

How to replace down arrow with text in a combobox in JavaFX


I'm trying to remove the down arrow from a combobox. All the solutions I have found just make the arrow disappear, for example this one.

Is there a way to remove completely the space where the arrow appears and fill the box just with the text of the selected choice?


Solution

  • If you want to completely elimnate the arrow & arrow button space, you can try with the below custom ComboBox.

    The below code is setting the arrow button and arrow nodes size to 0 and asking to rerender the comboBox. The null check is to let this changes apply only once.

    public class MyComboBox<T> extends ComboBox<T>{
        Region arrowBtn ;
    
        @Override
        protected void layoutChildren() {
            super.layoutChildren();
            if(arrowBtn==null){
                arrowBtn= (Region)lookup(".arrow-button");
                arrowBtn.setMaxSize(0,0);
                arrowBtn.setMinSize(0,0);
                arrowBtn.setPadding(new Insets(0));
    
                Region arrow= (Region)lookup(".arrow");
                arrow.setMaxSize(0,0);
                arrow.setMinSize(0,0);
                arrow.setPadding(new Insets(0));
    
                // Call again the super method to relayout with the new bounds.
                super.layoutChildren();
            }
        }
    }
    

    UPDATE :

    Based on the suggestion of @kleopatra, we can get the same behaviour using css as well (without the need to create a new class for ComboBox).

    .combo-box .arrow-button,
    .combo-box .arrow{
       -fx-max-width:0px;
       -fx-min-width:0px;
       -fx-padding:0px;
    }
    

    The below image will tell you the difference of a normal combox box and this custom combo box. The left one is the normal comboBox, you can see the list cell when inspecting with ScenicView. The right one is the custom one. The list cell is completely occupied suppressing the arrow space.

    enter image description here