1

I have a little application that opens a fileChooser when clicking a button and, after choosing a file, works with the contents of it. So, let's say we have this pseudo-code:

    File file = new File();
    JFileChooser fileChooser = new JFileChooser();

    [...]

    actionPerformed() {
      file = fileChooser.getSelectedFile();
      doStuffWithFile(file);
    }

At this point, it seems the code is taking on a procedural style, because everything that happens with file now actually happens while still inside that actionPerformed()-method. I'm not sure if this ok.

Is this okay coding style? Intuitively, I would want to end actionPerformed() and have the methods to work on my file called from somewhere else. But how would I do that?

An idea would be to just set the new value of file inside actionPerformed(). Then I could get that value with a getter. But how so? It should be the next thing that happens.

I've seen a propertyChangeListener here at stackoverflow, but I'm not sure if that's the right thing, too.

John Smith
  • 23
  • 8
  • *"`file = fileChooser.getFileName();`"* `file` is presumably a `String` so the first advice I would offer is. If you have a `File` and a method does something with a `File`, pass a `File` rather than a `String` that might represent the path. – Andrew Thompson Nov 21 '12 at 01:01
  • I'm sorry, _file_ is actually a File-object. I made a mistake in the example shown above, but I corrected it. – John Smith Nov 21 '12 at 01:07
  • For better help sooner, post an [SSCCE](http://sscce.org/) (as opposed to pseudo-code *or* code snippets). – Andrew Thompson Nov 21 '12 at 01:10

1 Answers1

0

One option is multithreading. It would still do everything, but not in the event thread. for example:

actionPerformed(){
    new Thread(){
        public void run(){
            file = fileChooser.getSelectedFile();
            doStuffWithFile(file);
        }
     }.start()
}
BillThePlatypus
  • 362
  • 1
  • 14
  • Multithreading had crossed my mind, but seeing your suggestion makes me believe that it probably is acceptable coding-style to just go about the actionPerformed()-method the way I already did. Everything else seems more complicated and I don't know if that's worth the hassle. – John Smith Nov 21 '12 at 01:36
  • The biggest thing here is that while the actionPerformed method is running, the gui freezes. This can be a major annoyance to have the gui freeze while something loads. This is why very little is put in the actual actionPerformed() method. To see for yourself, put `while(true);`in the method (though you'll have to kill it manually) – BillThePlatypus Nov 21 '12 at 02:06
  • That's a good point and I've encountered this problem just recently, too. So do you think going multi-threaded is the best way here? – John Smith Jan 30 '13 at 20:52