Originally posted by Donald Hume:
Ya know what! I actually tried that but stuck it in up top when JFrame j = new JFrame() was first called. Thanks a lot for the placement.
Yup, you can't do it in the variable declaration.
Originally posted by Donald Hume:
but... I've had this problem on other classes as well -- ones that didn't have a gui such as below:
. . .
What then?
This one's a little different. In this case, the sequence is running in a different
thread. If we place some additional System.out statements in the code -- before and after calling the go() method, and before and after the calling the sequencer.start() method -- we can see what is happening:
When we run the code, we get the output:
This shows that both the go and start method return, but stuff is still happening. In other words, the sequencer is running is a separate thread. (I'm not sure if you have gotten to Threads yet; I can't remember if they are before or after where you are in the book.)
I'm not very familiar with the Sequencer class since I've never really used it. But a quick look shows there is a isRunning() method that tells us if the sequencer is still running. I was looking to see if there a method that blocks (that is waits until something is finished running), but I didn't see one. So what we can do is this:
Now when we run, the output is:
Notice the "After go" never prints. More on that in a moment. The reason we use the Thread.sleep(500) is because just doing:
would cause a very tight running loop, which will spike the CPU. As an alternative to Thread.sleep(), if you are using Java 5 or later, you can use
TimeUnit.SECONDS.sleep(1) to sleep for a second, or TimeUnit.MILLISECONDS.sleep(500) for a 1/2 second, or any variation. I personally find the TimeUnit.XYZ.sleep() methods clearer, especially when sleeping for long times.
Now back to the "After Go" not printing. In the current form we are exiting the code in an unusual place... in the middle of the go() method. This makes the code hard to follow and trace, and potentially error prone. So what we can do is this. Make the Sequencer an instance variable (a.k.a a field) and then either put the code that waits for the sequencer to finish in the main method, or in a separate method that is called in the main method. The second option is a bit cleaner looking. So we end up with:
And when run, we get:
This way the code exits nicely from the main method.
Of course, you can then remove the System.out statements. Later in your programming experience, you'll learn about logging frameworks and how they can be used to turn such debugging output on and off very easily. But for now you can use System.out.
I hope that helps.
[ August 04, 2008: Message edited by: Mark Vedder ]