2014-01-05 27 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