两行显示ComboBox项,而不是一行显示

时间:2019-08-02 11:52:39

标签: javafx combobox

我当前正在使用JavaFx ComboBox,并且从XML文件加载选项。 我的问题是某些物品太长且不合适: enter image description here

我尝试使用CSS宽度:

   .combo-box {
        -fx-pref-width: 300;
    }
    .combo-box-popup > .list-view {
        -fx-pref-width: 300;
    }

enter image description here

是否可以两行显示ComboBox项目,而不是一行显示?

1 个答案:

答案 0 :(得分:2)

您将要为CellFactory设置自定义ComboBox。在我们构建的新ListCell中,我们可以使用一个简单的Label来为我们包装文字。

这是一个完整的示例,可以演示:

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.Label;
import javafx.scene.control.ListCell;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ComboBoxTextWrap extends Application {

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

    @Override
    public void start(Stage primaryStage) {

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

        // The ComboBox
        ComboBox<String> comboBox = new ComboBox<>();

        // Sample data
        comboBox.getItems().addAll(
                "Shorty",
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
                "Shorty Jr.",
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        );

        // Create our custom cells for the ComboBox
        comboBox.setCellFactory(param -> new ListCell<String>() {

            // Create a Label to store our text. We'll set it to wrap text and it's preferred width
            final Label label = new Label() {{
                setWrapText(true);
                setPrefWidth(200);
            }};

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setGraphic(null);
                } else {
                    // Add our text to the Label
                    label.setText(item);
                    setGraphic(label);
                }
            }
        });

        // Add the combobox to the layout
        root.getChildren().add(comboBox);

        // Show the stage
        primaryStage.setScene(new Scene(root));
        primaryStage.setTitle("Sample");
        primaryStage.show();
    }

}
  

结果:

screenshot

相关问题