原创

如何在JavaFX中使用CSS设置TableView列宽? JavaFx TableColumn 宽度在 CSS 中使用 em 单位

温馨提示:
本文最后更新于 2024年04月12日,已超过 48 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

This is my code:

public class JavaFxTest7 extends Application {

    private static class Student {

        private int id;

        private int mark;

        public Student(int id, int mark) {
            this.id = id;
            this.mark = mark;
        }

        public int getId() {
            return id;
        }

        public int getMark() {
            return mark;
        }
    }

    private TableView<Student> table = new TableView<>(FXCollections.observableList(
            List.of(new Student(1, 3), new Student(2, 4), new Student(3, 5))));

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

    @Override
    public void start(Stage primaryStage) {
        var idColumn = new TableColumn<Student, Integer>();
        idColumn.setCellValueFactory((data) ->  new ReadOnlyObjectWrapper<>(data.getValue().getId()));
        var markColumn = new TableColumn<Student, Integer>();
        markColumn.setCellValueFactory((data) ->  new ReadOnlyObjectWrapper<>(data.getValue().getMark()));
        markColumn.setMaxWidth(200);//this code works
        markColumn.setMinWidth(200);//this code works
//        markColumn.setStyle("-fx-min-width: 200; -fx-max-width: 200;");//this code doesn't work
        table.getColumns().addAll(idColumn, markColumn);

        VBox root = new VBox(table);
        var scene = new Scene(root, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

If I set column width using Java:

 markColumn.setMaxWidth(200);
 markColumn.setMinWidth(200);

I get:

enter image description here

But if I set column width using CSS:

 markColumn.setStyle("-fx-min-width: 200; -fx-max-width: 200;");

I get:

enter image description here

Could anyone say how to set column width using CSS?

正文到此结束
热门推荐
本文目录