java - How can I manage to make a line of code run once? -
when form opens, runs song. when go option frame , come main frame, re-runs code. did while loop , works , thing should declare initial value? if declare on windowopened
resets 0 doing loop again.
my code in openedwindow
event
int sound = 0; while (sound < 1) { try { inputstream test = getclass().getclassloader().getresourceasstream("musics/menu.wav"); audiostream audio = new audiostream(test); audioplayer.player.start(audio); } catch (exception e){} sound = sound + 1; } }
the inputstream , audiostream should instance variables of object. if residing in function openedwindow
, garbage collector after function has finished running.
instead, should instantiate them in class needs access them, possibly in constructor method.
also, make sound variable instance variable of class too. way won't reset each time openedwindow
called.
or instead use boolean flag variable indicate if sound has been played:
class mywindowlistener implements windowlistener { boolean soundplayed = false; ... public void windowopened(windowevent e) { if (!soundplayed) { // play sound soundplayed = true; } } }
Comments
Post a Comment