I an trying out a HTTP link to download using a GUI which when CLicked Start Download button will start download, Download is working but Label is not changing when download is started as declared in ActionListener. Please help me.
Here’s the code
Label should change when download is started and when completed.
public class SwingGUI2 extends javax.swing.JFrame {
private javax.swing.JLabel jLabel1;
private javax.swing.JButton jButton1;
private URLConnection connect;
private SwingGUI2() {
setLayout(new FlowLayout());
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("");
add(jLabel1);
jButton1 = new javax.swing.JButton();
jButton1.setText("Start Download");
add(jButton1);
jButton1.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed(e);
}
});
pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel1.setText("Download Started"); //NOT WORKING
try {
String DownURL = "http://www.number1seed.com/music/flymetothemoon.mp3";
URL url = new URL(DownURL);
connect = url.openConnection();
File file = new File("download");
BufferedInputStream BIS = new BufferedInputStream(connect.getInputStream());
BufferedOutputStream BOS = new BufferedOutputStream(new FileOutputStream(file.getName()));
int current;
while((current = BIS.read())>=0) BOS.write(current);
BOS.close();
BIS.close();
jLabel1.setText("Completed"); //NOT WORKING
} catch (Exception e) {}
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException {
try {
javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (IllegalAccessException ex) {
Logger.getLogger(SwingGUI2.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(SwingGUI2.class.getName()).log(Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SwingGUI2 gui = new SwingGUI2();
gui.setVisible(true);
gui.setSize(300,200);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
You are trying to run the download from the Event Dispatcher Thread, causing your GUI to freeze whilst the task is being performed.
Have a look at SwingWorker to execute the download task as a background thread. Your
actionPerformedmethod should be something like this:NB: Make sure you do not swallow the exception in this catch, else you won’t be able to see if anything wrong occurs.