This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Hello, As a part of my application I have a I/O method that stores all the positions of the start of the file lines in an ArrayList. It gets called when the user selects the file from a file chooser through the gui. The problem is that when the method is called a part of my gui disappears. I've read alot about threads and the SwingWorker but still not clear on how to implement these into my app. Would someone show me how to get this method to run in a new thread? I'm hoping this will keep the gui from flickering or disappearing when this method is executing. Thank you. Here's the code...
You are correct in your assumption. Using the Swing event thread (i.e. the one that notifies your class of GUI events) to run application logic will cause the GUI to be unresponsive until the application logic returns. You have a classic producer-consumer problem here: some action produces a File in need of processing, and your method above is the consumer. It will take a bit more than just changing the one method above to implement a multi-threaded solution, but it isn't too complicated. Check out the Java Tutorial: Threads. It discusses the various problems that can creep up when using threads and has a simple example of a producer-consumer program.
Ignore exceptions at your peril. You should either attempt to rectify the situation or provide feedback to the user in exceptional cases. At the very least, use e.printStackTrace() to get a stack dump. As you have them now you will never know if an exception occurs, and your user may just figure the program's is unusable. Second, it's bad form to create a thread and let it run through once. Threads aren't free. They require processor time and native resources to allocate. Creating a new thread for each loadFile() call probably costs you more than your previous single-threaded design. Put a while(true) loop in your run() method and use wait() and notifyAll() to control it (explained in the Java Tutorial).
Should I do the thread work in the mouse listener?
I doubt that the overhead of invoking openFile() is causing the delay.