首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用JavaFX对齐列表视图的内容

使用JavaFX对齐列表视图的内容
EN

Stack Overflow用户
提问于 2018-07-29 02:47:38
回答 1查看 1.7K关注 0票数 0

我正在尝试将列表视图的内容居中对齐

代码语言:javascript
复制
private ListView<String> library = new ListView<String>();
ObservableList<String> libraryList = FXCollections.<String>observableArrayList();

我已经找到了用CSS和XML来做这件事的方法,但是我正在寻找用java做这件事的方法,有人知道吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-29 03:07:03

您将需要对ListView使用自定义CellFactory和自定义ListCell

下面是一个完整的示例:

代码语言:javascript
复制
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) {

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

        ListView<String> listView = new ListView<>();

        // Setup the cell factory for the listview. It will hold lists of HBoxes that can be aligned
        listView.setCellFactory(stringListView -> new CenteredListViewCell());

        // Sample data
        listView.getItems().setAll("One", "Two", "Three", "Four");

        root.getChildren().add(listView);

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

final class CenteredListViewCell extends ListCell<String> {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setGraphic(null);
        } else {
            // Create the HBox
            HBox hBox = new HBox();
            hBox.setAlignment(Pos.CENTER);

            // Create centered Label
            Label label = new Label(item);
            label.setAlignment(Pos.CENTER);

            hBox.getChildren().add(label);
            setGraphic(hBox);
        }
    }
}

您要做的是创建一个使用HBox作为其主要内容的自定义CenteredListViewCell。通过设置HBox的对齐方式,您可以将Label居中。

然后在控制器中有了listView.setCellFactory(stringListView -> new CenteredListViewCell());,您就告诉ListView使用自定义单元而不是标准的Java实现。

这可能会被简化,我欢迎评论和编辑!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51574266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档