Java 查找Panel 里的某个组件 比如 按钮

遇到到一个需求,需要获取界面里的一个按钮,但是这个按钮是封装的父类嵌入的,知道label 的值。

 

写了一个递归获取它

 1 private JButton LookupTheButton(Component container, String label)
 2     {
 3         if (container instanceof JButton)
 4         {
 5             if (((JButton)container).getText().contains(label))
 6             {
 7                 return ((JButton)container);
 8             }
 9         }
10         else if (container instanceof Container)
11         {
12             for (Component compt : ((Container)container).getComponents())
13             {
14                 JButton tmpBtn = LookupTheButton(compt, label);
15                 if (null == tmpBtn)
16                 {
17                     continue;
18                 }
19                 else
20                 {
21                     return tmpBtn;
22                 }
23             }
24         }
25         
26         return null;
27     }

 

posted on 2023-02-14 17:22  皖南  阅读(116)  评论(0)    收藏  举报