62,635
社区成员




import java.util.List;
import java.util.LinkedList;
import java.awt.Component;
import java.awt.Container;
/**
* SwingUtil - Swing Tool Methods.
* @author SageZk(张长弓)
* @version 0.6
*/
public class SwingUtil {
private SwingUtil() { /*禁止创建此类的实例*/ }
/**
* 递归获取指定容器内的所有指定类型的组件。
* @param con 要搜索的容器
* @param cls 搜索的组件类型
* @return 搜索到的组件列表
*/
private static List<Component> getAllComponents(Container con, Class cls) {
if (con == null || con.getComponentCount() == 0) return null;
List<Component> coms = new LinkedList<Component>();
List<Container> cons = new LinkedList<Container>();
Component[] cs = con.getComponents();
for (Component c : cs) {
if (c.getClass() == cls) {
coms.add(c);
} else {
cons.add((Container) c);
}
}
for (Container c : cons) {
List<Component> list = getAllComponents(c, cls);
if (list != null) coms.addAll(list);
}
return coms;
}
/**
* 获取指定的容器内的所有指定类型的组件。
* @param con 要搜索的容器
* @param cls 搜索的组件类型
* @return 搜索到的组件数组
*/
public static Component[] getFrameComponents(Container con, Class cls) {
if (con == null || cls == null) throw new NullPointerException("con or cls is null");
List<Component> list = getAllComponents(con, cls);
if (list == null) return new Component[0];
return list.toArray(new Component[list.size()]);
}
}
public static JPanel initPage(JPanel page) {
Component[] cs = getFrameComponents(page, JButton.class); //搜索页面中所有 JButton
for (int i = 0; i < cs.length; ++i) {
JButton btn = (JButton) cs[i];
//根据权限启用或禁用按钮
}
return page;
}
JPanel page = initPage(new PageJPanel()); //PageJPanel 是你自己的页面类