在家里,扩展了今年冬天的课堂作业,试图让它在运行时更新一个 GUI 元素,以显示他循环的进度。
预期的功能是,当它通过字符串时,处理每个字符,从 GUI 类传入的 JLable在每次循环迭代时更新以显示通过字符串的进度。但是,发生的情况是它只会在循环之后更改标签上显示的内容,在最终Thread.sleep (1000)过期之后(我不知道它是在合成器关闭之前还是之后,不要认为它会相关:/)。
在这一点上,我想就如何让 JLabel 的“进度”在循环到期之前更改为“应该显示”文本提出建议——一些与我的问题无关的代码已被删除以保护效率。
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.MidiChannel;
import javax.swing.JLabel;
public class SoundPlayer {
/*Deceleration of private variables for the class*/
/*Constructor that assighns variables and triggers doPlay()method.
There is a reference to the JLabel 'Progress' passed in and declared beforehand,
so there is access.*/
}
public void doPlay() {
int totalSound;
playNumTimes = 1;
defaultTime = true;
sound = 0;
extraSound = 0;
try { //Opens ability to play the music.
Synthesizer synth = MidiSystem.getSynthesizer();
synth.open(); //Will likely play sound, so opens channel.
MidiChannel[] channels = synth.getChannels();
musicNotes += "."; //illegal character will mark end of string to play.
//Examines each char of the String and acts accordingly.
for (count = 0; count < musicNotes.length(); count++) { //For each char in the input.
if (processChar(musicNotes.charAt(count))) { //If processed char is illegal and triggers a sound, play it!
totalSound = extraSound + sound; //Combines from given note and the < and >s.
progress.setText("Should show");
//PLAYS SOUND HERE!
channels[channel].noteOn(totalSound, volume);
Thread.sleep(300 * playNumTimes); //Plays sound a number times equal to times.
channels[channel].noteOff(totalSound);
//After plays, resets values.
playNumTimes = 1;
defaultTime = true;
sound = 0; //Sound of 0 used to indicate no char has been assigned to the sound.
}
}
Thread.sleep(1000); //Wards against synthesizer from being closed prematurely and cutting off sound.
synth.close(); //Closes after loop is finished.
}
catch (Exception e){
e.printStackTrace();
}
}