2012-04-29 6 views
4

私はオプションのpannelをコーディングしています。アプリケーションを開発する際に、より多くのオプションを高速に追加できるように、すべての入力コンポーネントをFrame、私はconfigから値をロードし、対応するテキストを設定する必要がありますが、フィールドからコンポーネントのテキストを取得できないようです。 私が取得しています:
例外スレッドで "AWT-EventQueueの-0" java.lang.RuntimeException:互換性のないソースコード - 誤っSYMタイプ:java.awt.Component.setText
ノンブル:サーバーCLASE:クラスのjavax。ここでJava、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

* "アプリケーションを開発している間に、より多くのオプションをより速く追加できるようにするために、すべての入力コンポーネントをフレームに入れることを決めました" *大きなバケットで終わる可能性があります。私にもちょっと感銘を受けた。すばやくフレームを追加すると、フレームは何をしなければなりませんか? –

答えて

12

をswing.JTextField:

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

コンパイラは、唯一のコンポーネントとしてcompList.get(i)を見ています。 JTextFieldメソッドを使用するには、まずこれをJTextFieldとしてキャストする必要があります。

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

あなたの計画はここで私にはクルーギーであり、非常に非OOPsにも似ているようです。

おそらくMap<String, JTextField>を作成し、JTextFieldが表すものを表すStringに関連付けられたテキストフィールドに保持されているStringを取得するためのパブリックメソッドを提供したいとします。

+0

ありがとう!、両方の答えは完璧です! – Lautaro

7

あなたはこのようなものを使用する必要があります:代わりにあなたが行ってきたgetClass().toStringチェックの

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

を。

+0

良い提案、1 + –

+0

ありがとう!、両方の答えは完璧です! – Lautaro

関連する問題