Hello! I've written a couple of Java programs before that used Swing graphics, but this is the first time I've incorporated sound. Right now, the program has a ship traveling on the water which will shoot at planes. Before I tried adding sound, the ship moved smoothly, and I could fire rapidly. As soon as I added sound (the playShot() method below), every time I press the 'z' key to fire, the whole Swing screen freezes for about a half second, which totally messes up the game. Does anybody know how to fix this? Thank you in advance!
You need to run the MIDI/sound code in a thread other than the EDT. For better understanding, go through Concurrency in Swing.
A separate issue that can also needlessly slow down repainting (but minutely) is constructing a new Color object in paintComponent(...). since the Color is constant, it should be created as such: as a final static field.
Also, Swing was designed to use Key Bindings. It may appear to be more complicated than a AWT-style KeyListener, but it really doesn't take long to understand and is way more flexible and reliable.
There are no new questions, but there may be new answers.
One more comment: never test the equivalence of a boolean to true or false; it's redundant and a minor typo can lead to a sometimes difficult-to-debug error.An exercise for you: what's the minor typo I'm referring to?
Joined: Jan 25, 2012
I got it to work! Just in case somebody else has this problem and googles it, here's what happened. On Darryl's advise, I learned about threads, and I put the sound player in a thread. This improved things. After I pressed the "z" key, the ship continued to move smoothly. However, there was still a half-second delay before I heard a shot, and after a bunch of shots were fired, the screen started freezing again and eventually crashed. I then figured out that the command
sequencer = MidiSystem.getSequencer();
needs to be done only once. The new code is below.
Oh yeah, the answer to the exercise is that you might forget to type two equals signs instead of one. I've never done this for a boolean, but I did do it for an int once. That was an annoying bug.