在组合框中选择文本对齐

问题描述 投票:1回答:1

我有一个JavaFX的组合框几个文本的选择。如果选择使用居中对齐,而不是左对齐,这将是不错,但我还没有想出如何做到这一点。

以下是我使用的样式。我添加了条款“-fx文本对齐:中心;”但对ComboBox中字符串的位置没有影响。

    normalStyle = "-fx-font-family:san serif;"
            + "-fx-font-size:12;"
            + "-fx-text-alignment:center;"
            + "-fx-font-weight:normal;";

样式连接到组合框,如下所示:

     cbChoices.setStyle(normalStyle);

我注意到的是,大小和组合框项的权重将上述情况,但不对齐的变化作出反应。

我不希望空间添加到我的字符串的开始,让他们排队。有另一种方式?

java javafx javafx-8
1个回答
3
投票

您需要将ListCell内设置的样式上的每一个人ComboBox,而不是在ComboBox本身。

您可以通过提供与ListCell方法自己setCellFactory()实现这样做:

    // Provide our own ListCells for the ComboBox
    comboBox.setCellFactory(lv -> new ListCell<String>() {

        // We override the updateItem() method
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);

            // Set the style for this ListCell
            setStyle("-fx-alignment: center");

            // If there is no item for this cell, leave it empty, otherwise show the text
            if (item != null && !empty) {
                setText(item);
            } else {
                setText(null);
            }
        }
    });

示例应用程序:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ComboBoxAlignment extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple interface
        VBox root = new VBox(5);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);

        // Simple ComboBox with items
        ComboBox<String> comboBox = new ComboBox<>();
        comboBox.getItems().addAll("Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet");

        // Provide our own ListCells for the ComboBox
        comboBox.setCellFactory(lv -> new ListCell<String>() {

            // We override the updateItem() method
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                // Set the style for this ListCell
                setStyle("-fx-alignment: center");

                // If there is no item for this cell, leave it empty, otherwise show the text
                if (item != null && !empty) {
                    setText(item);
                } else {
                    setText(null);
                }
            }
        });

        root.getChildren().add(comboBox);

        // Show the Stage
        primaryStage.setWidth(300);
        primaryStage.setHeight(300);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
}

结果:

screenshot

© www.soinside.com 2019 - 2024. All rights reserved.