2014-01-05 29 views
1

我在try方法中設置了一個java bean。正在讀取文本文件,並且讀取的文本用於設置java bean。獲取在try方法中設置的Java bean

public class mainDisplay extends JPanel{ 



private imageDisplay id; 

public mainDisplay() 
{ 

    String path; 



     while (1==1) { 

      try { 

       FileInputStream roadMap = new FileInputStream("C:\\Users\\Public\\Desktop\\write.txt"); //path to the text file generated 
       DataInputStream route = new DataInputStream(roadMap); //importing the data from the text file 
       BufferedReader readMe = new BufferedReader(new InputStreamReader(route)); 
       pathOfspeed = readMe.readLine(); 
       // id = new imageDisplay(path); 

       Constants.getInstance().getBean().setPath(path); 
       try { 
        Thread.sleep(40); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
       } 




      } catch (Exception e) {     
       System.err.println("error:" + e.getMessage()); 
      } 

      System.out.println(Constants.getInstance().getBean().getPath()); 


     } 



} 

這是來自文本文件閱讀器的代碼和設置Bean的代碼。

這裏是從bean類的代碼:

public class Paths implements java.io.Serializable{ 

    public String url; 

    public Paths(){} 

    public void setPath(String name){this.url=name;} 

    public String getPath(){return url;} 

} 

然後我有我的常量類

public class Constants { 
private static Constants instance; 
private Paths bean; 

private Constants() { 
    bean=new Paths(); 
} 

public static synchronized Constants getInstance() { 
    if (instance == null) { 
     instance = new Constants(); 
    } 
    return instance; 
} 

public Paths getBean(){ 
    return bean; 
} 

public Paths setBean(Paths p){ 
    bean = p; 

    return p; 
} 

}

然後當我試圖讓這個Bean從出現我的問題另一類:

String imageUrl=Constants.getInstance().getBean().getPath(); 

    public test() { 

     System.out.println(imageUrl); 

    } 

我每次都得到空。文件讀取器需要保持不變,因爲文本文件中的行每分鐘都在變化,我需要傳遞給另一個使用它的類。

有人可以給我一些關於下一步做什麼的建議嗎?

謝謝

回答

2

問題出在你的Constants類中。

你做的每一次:

Constants.Bean 

返回這當然包含返回到您的getPath方法的空url變量新創建Path類。

你應該爲你的Constants類使用一個Singleton。

修改您的常量類:

public class Constants { 
    private static Constants instance; 
    private Paths bean; 

    private Constants() { 
    bean=new Paths(); 
    } 

    public static synchronized Constants getInstance() { 
    if (instance == null) { 
     instance = new Constants(); 
    } 
    return instance; 
    } 

    public Paths getBean(){ 
    return bean; 
    } 

    public Paths setBean(Paths p){ 
    bean = p; 
    } 

} 

寫入使用路徑變量:

Constants.getInstance().getBean().setPath("your path"); 

讀取路徑變量;

Constants.getInstance().getBean().getPath(); 
+0

我得到一個錯誤:無法解析方法的getPaths – user

+0

我把一個簡單的錯誤代碼......現在嘗試,方法名是當然的getBean的()。你不是在用某種代碼完成的IDE嗎?如果我的答案解決了您的問題,請不要忘記接受它:) – elbuild

+0

代碼現在運行,但我仍然從新代碼中得到測試類的空輸出。 – user