I'm trying to make an mp3 player using swing and when i play a song my jbutton play stays stucked and i can't press any other buttons from my app.I tried to use threads and it didn't worked, here is my play function code.
public static void fplay()
{
Runnable fplay = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(!songs.isEmpty())
{
for(int j=0;j<songs.size();j++)
{
System.out.println(path+"\\"+songs.get(j));
file = new File(path+"\\"+songs.get(j));
try {
fis = new FileInputStream(file);
player = new AdvancedPlayer(fis);
graphics.label.setText(songs.get(j).toString());
player.play();
}catch(Exception e) {
}
}
}else
JOptionPane.showMessageDialog(null, "No directory selected","Error",
JOptionPane.ERROR_MESSAGE);
}};
SwingUtilities.invokeLater(fplay);
}
The invokeLater(...) method adds code to the end of
Event Dispatch Thread (EDT). So this means the audio is still executing on theEDTand the GUI can't respond to events.Instead you need to start a separate
Thread, so the audio doesn't prevent the GUI from responding to events.So you want to pass the
Runnableto aThreadand start theThread.Read the section from the Swing tutorial on Concurrency for more information about the EDT.
Well, that is the proper solution. I can't guess what you did wrong, although you should never have an empty catch block. How will you know what the error is if you don't display anything?
The tutorial on
Concurrencyalso shows how to use a SwingWorker which could be a better solution for you.