【问题标题】:How can I get all the components of a panel in Java Swing?如何在 Java Swing 中获取面板的所有组件?
【发布时间】:2013-03-21 14:17:59
【问题描述】:

如何在 Java Swing 中获取面板的所有组件?

在 C# 中有没有类似 foreach 的方法来处理 JPanel 的所有子组件?

【问题讨论】:

  • 在询问之前,有时尝试显而易见的事情是值得的...... :)
  • 你知道有 api 文档,你知道吗:-) 提示:还要看看从 super 继承的方法。

标签: java arrays swing jpanel jcomponent


【解决方案1】:

你可以使用getComponents的方法:

Component[] components = jpanel.getComponents();

【讨论】:

  • 这将获取子组件,而不是那些组件的子组件。例如,如果您的面板具有诸如 CollapsiblePanel 之类的容器,则集合 components 将包含对该 CollapsiblePanel 的引用,但不包含其子组件。
【解决方案2】:

如果您有多个 JPanel 并且想要获取所有组件名称,请尝试以下操作:

public void getAllComponetsNameInJPanels(JPanel... panels) {
    Component[] components;
    String componentName;
    for (JPanel panel : panels) {
        components = panel.getComponents();            
        for (Component compo : components) {
            componentName = compo.getClass().getName();
            System.out.println(compo.getClass().getName().substring(componentName.indexOf("swing.") + "swing.".length(), componentName.length()));
        }
        System.out.println("=====================");
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-16
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多