Hi, I'm really new to programming and Java but I'm really getting into to it. I'm writing a small program that is going to use the Swing Timer and I've got it to work but I'm not sure about two things.
Question #1: This works but if I take the try statement that puts the thread to sleep it will not work. I don't understand why you'd need the thread to sleep. Shouldn't the scheduler run it right away?
Question # 2: I didn't see anything in the API or the tutorials about adding in a the Try-Sleep code. How would I know to do this (understanding Threads better I guess?)
Question # 3: in the import, this doesn't work but i thought adding " import javax.swing.*;" would also bring in the Timer class...?
Please use code tags round quoted code; they make it easier to read. Long time since I used Timers, but as far as I can remember:
There are two other classes called Timer; you can get confusion between them.
You have obviously got your delay of 6 seconds before "in actionevent" prints. That works correctly.
You have your 1 second delay before printing out "in go" correct.
You have obviously worked out how to use this Timer.
What you appear to have is three threads.
Main thread. This starts off your app, and starts whenever a main method is called.
Event dispatch thread. This is (or ought to be) started whenever you start off any Swing objects.
Another thread started by the Timer, let's call it timerThread.
They run rather like this
main---------> etc etc Starts off event dispatch thread (EDT). EDT--->print "in go"-->sleep 10 sec----------------------->------------------------------->nothing happens Starts off timerThread (TT) TT-->starts--->waits 6 seconds-->print "event" & make frame visible--->don't repeat.
There is a problem with Thread.sleep(); it may throw an InterruptedException if another Thread calls to interrupt it while "asleep." InterruptedException is a checked Exception so the try-catch is required.
Add a setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) call on your frame, so you can close the app with the close button.
Put something inside the catch block, so you can see whether the Thread is interrupted.
Consider whether you need the sleep call at all; it doesn't appear to do anything.
OR: Add something after the sleep() call so you can see when it finishes.