我需要能夠有一個類的組件列表和它們各自的變量名稱。我設法得到了GUI中所有組件的列表。但是,當我調用組件的getName方法時,返回null。有誰知道如何能夠獲得這樣一個組件的名稱嗎?如何獲取Java中的GUI組件的名稱?
這是迄今爲止的代碼:
public static void main(String[] args){
Calculator c = new Calculator();
List<Component> containers = getAllComponents(c.getContentPane());
for (int i = 0; i < containers.size(); i++) {
System.out.println(containers.get(i).getClass().getName());
System.out.println(containers.get(i).getName());
}
System.exit(0);
}
public static List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container) {
compList.addAll(getAllComponents((Container) comp));
}
}
return compList;
}
我確實設法獲取變量的名稱和類型......我想我可以繼續以這種方式實現...非常感謝您的幫助 – ict1991 2012-03-16 10:16:01