您不必revalidate
为了更改滑块而进入容器。
每次创建新播放器时使用这些行:
slider.setMinimum(0);
slider.setMaximum(duration);
slider.setValue(0);
new UpdateWorker(duration).execute();
其中duration
是保存歌曲持续时间的变量,以秒为单位。
这是更新滑块的代码(用作内部类):
private class UpdateWorker extends SwingWorker<Void, Integer> {
private int duration;
public UpdateWorker(int duration) {
this.duration = duration;
}
@Override
protected Void doInBackground() throws Exception {
for (int i = 1; i <= duration; i++) {
Thread.sleep(1000);
publish(i);
}
return null;
}
@Override
protected void process(List<Integer> chunks) {
slider.setValue(chunks.get(0));
}
}
现在滑块将向右移动,直到歌曲结束。
另请注意,除非您想使用自定义滑块,否则 JMF 通过player.getVisualComponent()
(参见此示例)提供了一个简单(且有效)的滑块。
更新
为了暂停/恢复工作线程(以及滑块和歌曲),这里有一个带有设置适当标志的按钮的示例。
private boolean isPaused = false;
JButton pause = new JButton("Pause");
pause.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
if (!isPaused) {
isPaused = true;
source.setText("Resume");
} else {
isPaused = false;
source.setText("Pause");
}
}
});
该方法doInBackground
应更改为:
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i <= duration; i++) {
if (!isPaused) {
publish(i);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
while (isPaused) {
try {
Thread.sleep(50);
continue;
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
return null;
}
相应地修改它以暂停/恢复歌曲以及滑块。
您还应该考虑@AndrewThompson 的回答。