[英]Why can't the setLayout method be used with an ArrayList of JPanel
I am quite new to swing and I had a question about layout managers. 我是新手,我对布局管理器有疑问。 When I use setLayout() to put a layout manager in place for a single container I have no issues.
当我使用setLayout()为单个容器放置布局管理器时,我没有任何问题。 Example:
例:
JPanel oneContainer = new JPanel();
oneContainer.setLayout(new GridBagLayout());
This works fine. 这很好。
What I want to do is set a certain layout manager for ever container in an ArrayList. 我想做的是为ArrayList中的容器设置某个布局管理器。 Is there any way of doing this without cycling through each element with a loop.
有什么方法可以做到,而无需循环遍历每个元素。
Example: 例:
ArrayList<JPanel> multipleContainers = new ArrayList<>();
multipleContainers.setLayout(new GridBagLayout());
(or something like that, you get the idea, I'm aware that the code provided is obviously erroneous, I'm also aware that to set a layout manager for a single ArrayList element I would just add .get(num) after the "multipleContainers") TIA (或者类似的东西,您知道了,我知道所提供的代码显然是错误的,我也知道要为单个ArrayList元素设置布局管理器,我只会在。之后添加.get(num) “ multipleContainers”)TIA
Sorry! 抱歉! You just have to suck it up and do it the hard way :) Actually it's not so hard with a for-each loop:
您只需要吸吮它并以困难的方式完成它即可:)实际上,对于for-each循环来说并不那么困难:
for (JPanel p : multipleContainers)
p.setLayout(new GridBagLayout());
Or, as you've already surmised, there's the old-fashioned way: 或者,正如您已经推测的那样,有一种老式的方式:
for (int i = 0; i < multipleContainers.size(); ++i)
multipleContainers.get(i).setLayout(new GridBagLayout());
I noticed that the type of multipleContainers is ArrayList, instead of JPanel. 我注意到,multipleContainers的类型是ArrayList,而不是JPanel。 So setLayout() does not work here.
所以setLayout()在这里不起作用。
If you want to setLayout() works, you need to iterate the ArrayList to get panels. 如果想让setLayout()起作用,则需要迭代ArrayList以获得面板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.