java - 获取组件对象的组件?

标签 java user-interface components

我只是为了自己的兴趣而尝试写以下内容:

public void enableComponents(boolean enable) {
    Component[] components = getContentPane().getComponents();

    for (int i = 0; i < components.length; ++i) {
        components[i].setEnabled(enable);
    }
// [...]

在“Component[]”数组中可以例如还有一个包含更多 GUI 元素的 JPanel。但我怎样才能访问它们呢?没有像“components[i].getCOmponents()”这样的方法吗?

最佳答案

awt 设计者将 Container 类作为一种特殊的组件,我也不明白为什么,但你可以利用这个特性。

要查找所有子组件,您可以检查该组件是否是容器。如果不是,则它不能有子组件。如果是,则转换为 Container 并访问它们。如果您还需要子子组件,请递归。

Component[] components = getContentPane().getComponents();

for (int i = 0; i < components.length; ++i) {
   if ((components[i] instanceof Container)) {
       Container subContainer = (Container)components[i];
       //do something here
   }else{
       //do something here
   }
}

关于java - 获取组件对象的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14797368/

相关文章:

java - websocket 消息会不会丢失?

java - 使用字符作为扫描仪的起点和终点

java - 如何迭代字符串数组,使每个值与其他每个值匹配一次且仅一次

c++ - QT-Graphics - 如何限制项目的移动

user-interface - 将接口(interface)与逻辑分离 - Java

java - src/test/中的 IntelliJ Idea JPA 实体

qt - 在 Qt 中旋转图像

javascript - 在 React Native 中通过子组件更新父组件

java - Android 组件 ClassNotFoundException

javascript - Angular 组件 : no template replace option?