You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX中for循环遍历数组仅显示最后一个元素问题求助

JavaFX GridPane 仅显示最后一个元素的问题解决

问题出在你每次向productGridPane添加Label时,都使用了相同的行列坐标(0, 0)。GridPane中同一位置的控件会被后续添加的覆盖,所以只有最后一个Label(Orange)能显示出来。

修正后的代码:

Product[] arr = new Product[2];
arr[0] = new Food("Apple", 3.44, "fruit", false);
arr[1] = new Food("Orange", 3.14, "fruit", false);

for (int i= 0 ; i < arr.length; i++) {
    Label label = new Label(arr[i].name);
    label.setPadding(new Insets(5, 5, 5, 5));

    // 将行索引设为i,每个Label放在不同行
    productGridPane.add(label, 0, i);
}

如果想横向排列,也可以把列索引设为i,行索引固定0:

productGridPane.add(label, i, 0);

这样每个Label会被放置在GridPane的不同位置,不会互相覆盖,两个元素的名称都会正常显示。

内容的提问来源于stack exchange,提问作者fatihcan8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 22:40:43