如何在JavaFX ChoiceBox中水平居中文本

时间:2016-05-20 18:37:48

标签: java javafx javafx-8

有没有办法在javafx.scene.control.ChoiceBox中水平居中文字?我希望将文本置于ChoiceBox中心,以及在选择值时打开的下拉列表。

1 个答案:

答案 0 :(得分:1)

根据@VGR的建议,我改变了我的实现以使用javafx.scene.control.ComboBox。然后,我创建了一个名为CenteredListCell的类:

import javafx.geometry.Pos;
import javafx.scene.control.ListCell;

public class CenteredListCell<T> extends ListCell<T> {

    /** Default constructor */
    public CenteredListCell() {
        setMaxWidth(Double.POSITIVE_INFINITY);
        setAlignment(Pos.BASELINE_CENTER);
    }

    @Override
    public void updateItem(final T item, final boolean empty) {
        super.updateItem(item, empty);
        setText(empty || item == null ? null : item.toString());
    }

}

接下来,我创建了以下实用程序方法(感谢@kleopatra获取导致runWhenSkinned的灵感):

private static void runWhenSkinned(final Control control, final Runnable operation) {
    final ReadOnlyObjectProperty<?> skinProperty = control.skinProperty();
    if (skinProperty.get() == null) {
        // Run after the control has been skinned
        skinProperty.addListener(observable -> Platform.runLater(operation));
    } else {
        // Run now, since the control is already skinned
        operation.run();
    }
}

public static <T> void center(final ComboBox<T> comboBox) {
    runWhenSkinned(comboBox, () -> {
        // Get the width of the combo box arrow button
        final Region arrow = (Region)comboBox.lookup(".arrow-button");
        final double arrowWidth = arrow.getWidth();

        // Create a centered button cell
        final ListCell<T> buttonCell = new CenteredListCell<T>();
        comboBox.setButtonCell(buttonCell);

        // Create an insets object with uneven horizontal padding
        final Insets oldPadding = buttonCell.getPadding();
        final Insets newPadding = new Insets(oldPadding.getTop(),
                arrowWidth, oldPadding.getBottom(), 0);

        // Replace the default cell factory
        comboBox.setCellFactory(listView -> new CenteredListCell<T>() {
            { setPadding(newPadding); }
        });
    });
}

最终结果是ComboBox在项目的按钮单元格和列表视图中都有居中文本。