gpt4 book ai didi

Java Swing 布局管理器循环引用被设置两次

转载 作者:行者123 更新时间:2023-12-02 00:06:17 24 4
gpt4 key购买 nike

任何人都可以解释为什么在下面的代码中设置两次循环引用吗?

//declare panel
this.cntnrPnl = new JPanel();
//define layout manager for the panel - but why circ ref?
this.cntnrPnl.setLayout(new BoxLayout(this.cntnrPnl, BoxLayout.Y_AXIS));

为什么需要显式地将 BoxLayout 链接回 JPanel 容器,而不是 JPanel.setLayout 在场景后面自行进行设置并使用 BoxLayout 中的 setter 来实现代码紧凑性?

例如:

this.cntnrPnl.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
//and then in JPanel.setLayout have something line
_layout.setContainer(this);

最佳答案

因为BoxLayout是一种特殊的布局,需要对其布局的目标容器的引用。并非所有布局管理器都是如此。在 setLayout() 方法中添加 BoxLayout 的特定情况会很丑陋。这也意味着 BoxLayout 在构建后将处于不稳定状态,因为它还没有强制性的目标容器。

相反也可以完成:让 BoxLayout 构造函数在目标容器上调用 setLayout(this) 。但不知道为什么还没有实现。

关于Java Swing 布局管理器循环引用被设置两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13810075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com