如何让ListView的宽度等于最宽的单元格?

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

我需要使 ListView 足以显示最宽的单元格(无需剪切),但仅此而已。例如,如果有三个宽度分别为 100px、200px、300px 的标签,则 ListView 宽度必须为 300px。

我尝试了以下代码,但没有成功:

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) {
        ObservableList<String> items = FXCollections.observableArrayList(
            "Short item",
            "A bit longer item",
            "This is a much longer item that needs more space"
        );

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

        ListCell<String> tempCell = new ListCell<>();
        double maxWidth = 0;
        for (String item : items) {
            tempCell.setText(item);
            double cellWidth = tempCell.prefWidth(-1);
            if (cellWidth > maxWidth) {
                maxWidth = cellWidth;
            }
        }

        listView.setPrefWidth(maxWidth);
        var tabPane = new TabPane(new Tab("Test"));
        HBox.setHgrow(tabPane, Priority.ALWAYS);
        var root = new HBox(listView, tabPane);
        Scene scene = new Scene(root, 800, 300);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ListView Width Example");
        primaryStage.show();
    }

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

谁能告诉我怎么做吗?

java javafx
1个回答
0
投票

我建议使用

Text
并添加类似 25 的宽度。

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class App extends Application {

    @Override
    public void start(Stage primaryStage) {
        ObservableList<String> items = FXCollections.observableArrayList(
            "Short item",
            "A bit longer item",
            "This is a much longer item that needs more space"
        );

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

        
        double maxWidth = 0;
        for (String item : items) {
            Text text = new Text(item);
            double cellWidth = text.getLayoutBounds().getWidth() + 25;
            if (cellWidth > maxWidth) {
                maxWidth = cellWidth;
            }
        }

        listView.setPrefWidth(maxWidth);
        var tabPane = new TabPane(new Tab("Test"));
        HBox.setHgrow(tabPane, Priority.ALWAYS);
        var root = new HBox(listView, tabPane);
        Scene scene = new Scene(root, 800, 300);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ListView Width Example");
        primaryStage.show();
    }

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

enter image description here

来自 如何计算 JavaFX 中字符串的像素宽度?

的想法
© www.soinside.com 2019 - 2024. All rights reserved.