简体   繁体   中英

How to wait for an attribution in startup() to complete before continuing?

I'm making a desktop application which watches a folder using watchservice from java.nio.file . But I need the gui to be loaded before I start watching, because the path to be watched is in a JFieldText on the UI.

public class FileArchiverApp extends SingleFrameApplication {

   static FileArchiverView gui;

@Override protected void startup() {
   gui = new FileArchiverView(this); //HERE0 I have to wait for this.
   show(gui);     
...
public static void main(String[] args) throws IOException {
   launch(FileArchiverApp.class, args);
....
   WatchService watcher = FileSystems.getDefault().newWatchService();
     // HERE1 while(gui==null) System.out.println("hi") ;
    try {
          Path dir = Paths.get(gui.getOriginPath()); // HERE2 I get nullpointer if gui was not ready
          WatchKey key = dir.register(watcher, ENTRY_CREATE );
    } catch ( Exception x) {
            System.err.println(x);
    }

    while(true){ /*wait for new file event loop*/ } 
}

The function getOriginPath() returns the getText() form the text field I mentioned.

In HERE0 is the attribution I mentioned. I get a nullpointer in HERE2 if gui wasn't ready. I've tried things. If I put that thing in HERE1 it works, but of course I don't want to do that.

How could I make it?

And its taking to long(like two seconds) or the gui to stop being null with this HERE1 I don't know if it is because of the println, but I was expecting it to be almost instantaneous. Is it normal?

Thanks.

Given the limited information posted, I have to make some assumptions. Assumption 1 is that you give the JTextField a default value and use that as the path to the file you wish to watch. Assumption 2 is that you have not coded with an eye towards MVC-like design.

If both are correct, then it sounds like you have the tail wagging the dog -- the view holding the critical data, not the model. Why not fix your problem by going towards MVC and not getting the critical data from the view but rather from the model. Start the model up first thing, including getting the default path from your program Properties, get your listener going, start your view, and then if the view asks the controller to change the watched file, have the controller change the model. And then listeners in the model will notify your any observers of change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM