2012-04-29 40 views
4

我正在編寫一個選項的pannel,爲了能夠在開發應用程序時更快地添加更多選項,我決定將所有輸入的組件都放在一個Frame中,我需要從配置中加載它們的值並設置相應的文本,但似乎無法從字段中獲取組件的文本。 我收到了:
線程「AWT-EventQueue-0」中的異常java.lang.RuntimeException:不可編譯的源代碼 - 錯誤的sym類型:java.awt.Component.setText
Nombre:server Clase:class javax。 swing.JTextFieldJava,Swing,獲取和更改所有輸入字段

private void loadConfigs() { 
    List<Component> compList = getAllComponents(this); 
    System.out.println("Tamaño "+compList.size()); 
    for(int i=0; i<compList.size();i++) { 
     if(compList.get(i).getName() != null) { 
      System.out.println("Nombre: "+compList.get(i).getName() +" Clase:"+ compList.get(i).getClass().toString()); 
      if(compList.get(i).getClass().toString().matches("class javax.swing.JTextField")) { 
       System.out.println("Machea load " +compList.get(i).getName() + compList.get(i).toString()); 
       compList.get(i).setText(rootFrame.config.get(compList.get(i).getName())); 
      } 
      else if(compList.get(i).getClass().toString().matches("class javax.swing.JCheckBox")) { 
       if (rootFrame.config.get(compList.get(i).getName()) == null) { 
        compList.get(i).setSelected(false); 
       } 
       else { 
        compList.get(i).setSelected(true); 
       } 
      } 
     } 
    } 
} 
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; 
} 
+1

*「並且能夠在開發應用程序時更快地添加更多選項,我決定將所有輸入的組件都放在一個Frame中*」這可能會以'在大桶中'結束,它會有對我來說同樣重要。框架與快速添加內容有什麼關係? –

回答

12

這裏:

compList.get(i).setText(....) 

編譯器只看到compList.get(i)作爲一個組件。要使用JTextField方法,您必須首先將其轉換爲JTextField。

((JTextField)compList.get(i)).setText(....) 

你在這裏的計劃對我來說似乎是非常糟糕,但非OOPs兼容。

也許你想創建一個Map<String, JTextField>,並給予類的公共方法來獲得與代表什麼JTextField中表示字符串相關的文本字段舉行的字符串。

+0

謝謝!,這兩個答案都是完美的! – Lautaro

7

您應該使用這樣的事:

if(compList.get(i) instanceof JTextField) { 
    JTextField field = (JTextField) compList.get(i); 
    field.getText(); // etc 
} 

代替getClass().toString檢查你一直在做的事情。

+0

好的建議,1+ –

+0

謝謝!,這兩個答案都是完美的! – Lautaro