【问题标题】:How to read the Components of panel in JTabbedPane and add result to the componets如何在 JTabbedPane 中读取 jpanel 的组件并将结果添加到组件中
【发布时间】:2014-05-09 06:10:20
【问题描述】:

我有一个 Swing GUI 应用程序,其中包含 JTabbedPane 和多个面板。 它有大约 9 个 Jpanel,在第一个 JPanel 中有四个 Jpanel,这些 Jpanel 包含一些摆动组件。 我已经设置了这些面板名称。

我的问题是:我可以在第一个选项卡面板中读取这些组件,但问题是无法获取面板的名称并继续进行。

代码如下:

1.,示例类:

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

public class Sample {

    public Sample() {}

    public List<Component> getComponents(int id , Object obj) {
        List<Component> result = new ArrayList<Component>();
        if (id == 1 && obj instanceof ExampleTab1) {
            Component[] component =((ExampleTab1)obj).getContentPanel().getComponents();
            for (Component comp : component) {
                if (comp instanceof JPanel) {                                              
                    String compName = ((JPanel)comp).getName().toString();
                    if (compName.equals("panelResult")) {
                        //do the stuff
                    }
                }
            }
        }
        return result;
    }
}

2.、ExampleTab1 类:

import javax.swing.JPanel;

public class ExampleTab1 {
    public ExampleTab1() { }
    public JPanel getContentPanel()  {
        JPanel contentPane = new JPanel();
        //all the components added to the panel 
        return contentPane;
    }
}

【问题讨论】:

  • 当你运行代码时会发生什么?
  • 为了尽快获得更好的帮助,请发布MCVE(最小完整且可验证的示例)。
  • 结果没有添加到 panelResult,但是当我列出组件时,我会得到所有组件

标签: java swing jpanel jtabbedpane


【解决方案1】:

如果你想从一个容器中获取所有元素(比如 JPanel 或 JTabbedPane 等),你需要手动收集它们,因为 getComponents() 只读取容器的直接子元素。

您需要在 Sample 类中添加以下函数:

public List<Component> getAllComponents(Container container) {
    Component[] components = container.getComponents();
    List <Component> result = new ArrayList<Component>();
    for (Component component : components) {
        result.add(component);
        if (component instanceof Container) {
            result.addAll(getAllComponents((Container) component));
        }
    }
    return result;
}

你需要替换以下代码:

Component[] component =((ExampleTab1)obj).getContentPanel().getComponents();
使用以下代码:
List&lt;Component&gt; components = getAllComponents(((ExampleTab1)obj).getContentPanel());
,如果您有没有名称的组件,请不要忘记对 getName() 函数进行空检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多