Aref Hoseinikia
Aref Hoseinikia

Reputation: 117

How to change text alignment of a combo box items in javafx?

I have a Combo Box in my app . I added some items as string to it . Items have left alignment . I want the right alignment . I searched a lot but i cant find anything. Thanks.

Upvotes: 0

Views: 3641

Answers (1)

Lukas Rotter
Lukas Rotter

Reputation: 4188

I figured out the following solution, although I'm not sure if it's a good one:

enter image description here


For button cell:

box.setButtonCell(new ListCell<String>() {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (item != null) {
            setText(item);
            setAlignment(Pos.CENTER_RIGHT);
            Insets old = getPadding();
            setPadding(new Insets(old.getTop(), 0, old.getBottom(), 0));
        }
    }
});

For popup list view:

box.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
    @Override
    public ListCell<String> call(ListView<String> list) {
        return new ListCell<String>() {
            @Override
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null) {
                    setText(item);
                    setAlignment(Pos.CENTER_RIGHT);
                    setPadding(new Insets(3, 3, 3, 0));
                }
            }
        };
    }
});

Upvotes: 5

Related Questions