组合框选择中的文本对齐

时间:2019-02-08 03:41:08

标签: java javafx javafx-8

我有一个带有多个文本选择的JavaFX ComboBox。如果选择使用居中对齐而不是左对齐,那会很好,但是我还没有弄清楚如何做到这一点。

以下是我使用的一种样式。我添加了子句“ -fx-text-alignment:center;”但这对组合框中字符串的放置没有影响。

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

样式如下所示附加到组合框:

     cbChoices.setStyle(normalStyle);

我注意到组合框条目的大小和重量将响应上述更改,但不会响应对齐。

我不想在字符串的开头添加空格以使它们对齐。还有另一种方法吗?

1 个答案:

答案 0 :(得分: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