【问题标题】:Why can't the setLayout method be used with an ArrayList of JPanel为什么 setLayout 方法不能与 JPanel 的 ArrayList 一起使用
【发布时间】:2017-10-17 16:35:06
【问题描述】:

我对 Swing 很陌生,我有一个关于布局管理器的问题。当我使用 setLayout() 为单个容器放置布局管理器时,我没有任何问题。示例:

JPanel oneContainer = new JPanel();
oneContainer.setLayout(new GridBagLayout());

这很好用。

我想要做的是为 ArrayList 中的容器设置一个特定的布局管理器。 有没有办法做到这一点,而不用循环遍历每个元素。

例子:

ArrayList<JPanel> multipleContainers = new ArrayList<>();
multipleContainers.setLayout(new GridBagLayout());

(或类似的东西,你明白了,我知道提供的代码显然是错误的,我也知道要为单个 ArrayList 元素设置布局管理器,我只需添加 .get(num ) 在 "multipleContainers" 之后) TIA

【问题讨论】:

  • Is there any way of doing this without cycling through each element with a loop. - 使用循环有什么问题???它的两行代码!!!
  • @camickr Lol 我只是好奇是否有办法做到这一点:) ...我不反对使用循环。
  • 即使有办法做到这一点,仍然会有一个循环。这只是一个你不必为自己编写的循环......
  • @KevinAnderson 假设我是代表优雅问的。

标签: java swing arraylist layout-manager


【解决方案1】:

对不起!你只需要接受它并以艰难的方式去做:) 实际上,使用 for-each 循环并不难:

for (JPanel p : multipleContainers)
    p.setLayout(new GridBagLayout());

或者,正如您已经推测的那样,有一种老式的方法:

for (int i = 0; i < multipleContainers.size(); ++i)
    multipleContainers.get(i).setLayout(new GridBagLayout());

【讨论】:

    【解决方案2】:

    我注意到multipleContainers 的类型是ArrayList,而不是JPanel。所以 setLayout() 在这里不起作用。

    如果你想 setLayout() 工作,你需要迭代 ArrayList 来获取面板。

    【讨论】:

    • 我知道这一点,我在上面提到过。
    猜你喜欢
    • 2016-08-30
    • 2015-09-25
    • 1970-01-01
    • 2021-08-06
    • 2021-12-25
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多