您可以將監聽器添加到GridPane中以獲取其子元素的大小,並根據子元素列表的大小更新子節點的佈局約束。
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.collections.ObservableList;
import javafx.geometry.*;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.stream.IntStream;
public class GridViewer extends Application {
@Override
public void start(final Stage stage) throws Exception {
ChartGrid grid = new ChartGrid();
grid.getChildren().setAll(
IntStream.range(1, 5)
.mapToObj(this::createLineChart)
.toArray(Chart[]::new)
);
stage.setScene(new Scene(grid));
stage.show();
}
class ChartGrid extends GridPane {
ChartGrid() {
setHgap(5);
setVgap(5);
setPadding(new Insets(5));
setPrefSize(500, 500);
Bindings.size(getChildren()).addListener((observable, oldSize, newSize) -> {
ObservableList<Node> nodes = getChildren();
for (int i = 0; i < newSize.intValue(); i++) {
GridPane.setConstraints(
nodes.get(i),
i/2, i % 2,
1, 1,
HPos.CENTER, VPos.CENTER,
Priority.ALWAYS, Priority.ALWAYS
);
}
});
}
}
private Chart createLineChart(int idx) {
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
LineChart<Number, Number> chart = new LineChart<>(xAxis, yAxis);
chart.setTitle("Chart " + idx);
chart.setMinSize(0, 0);
return chart;
}
public static void main(String[] args) throws Exception {
launch(args);
}
}
注:這個解決方案的一個重要組成部分,是設置圖表的minSize屬性爲0:
chart.setMinSize(0, 0);
這是因爲如果你的尺寸的可用面積GridPane小於圖表的最小大小(默認情況下不是0)的總和,那麼圖表將開始相互重疊,這不是您想要的。
你可以得到所述窗格的寬度,除以二,然後做同樣的高度?快速谷歌發現[這](http://stackoverflow.com/questions/12643125/getting-the-width-and-height-of-the-center-space-in-a-borderpane-javafx-2) – Taelsin
是我試過這個,但結果是滿意的,也不是很優雅。當我在網格中有4個圖表時,我試圖將每個人的prefWidth/Height設置爲GridPane尺寸的一半。不知何故,圖表仍然有不同的大小,從圖表1開始最大,圖表4最小:/ –