I am trying to implement an image using the method below, so that when the send action is performed, the GIF image should show within a specified time(As implemented by the threadRunner pause method).
The problem is it doesn’t show. And on testing, when I disable the stop() it appears at the same time as delIveryReport Textarea which shouldn’t be. How do I solve this.
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
threadRunner t = new threadRunner();
String fone = "";
SendSMS sms = new SendSMS();
String[] arMSISDN = msisdn.split(",");
for (int i = 0; i < arMSISDN.length; i++) {
fone = arMSISDN[i];
fone = fone.trim();
try {
Cursor cursor = new Cursor(Cursor.WAIT_CURSOR);
setCursor(cursor);
t.pause(loading);
sms.sendSMS(user, pass, fone, senderIDString, msgString);
} catch (Exception e) {
e.printStackTrace();
} finally {
Cursor normal = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(normal);
t.stop(loading);
deliveryReport.append(fone + ": " + sms.response + "\n");
}
}
// JOptionPane.showMessageDialog(rootPane, deliveryReport);
deliveryReport.setVisible(true);
jScrollPane2.setVisible(true);
redo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
redo.setForeground(new java.awt.Color(223, 90, 46));
redo.setText("Would you like to send another Message?");
yes.setEnabled(true);
no.setEnabled(true);
yes.setText("Yes");
no.setText("No");
back.setEnabled(false);
send.setEnabled(false);
}
THREADRUNNER
public void pause(JLabel label){
try {
Thread.sleep(5000);
label.setVisible(true);
} catch (InterruptedException ex) {
Logger.getLogger(threadRunner.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void stop(JLabel l){
l.setVisible(false);
}
It seems to me that your application is doing the actual work on the EDT, while your thread takes care of showing and hiding the progress label. I might be wrong, but if that is the case, then I’d recommend that you do the complete opposite of what you are doing. Updating SWING components should only be done from the EDT (Event Dispatch Thread) and no other threads.
If this is a SWING desktop application, then my recommendation would be that you take a look at SwingWorker which is a class that is specifically designed to handle long running tasks withough blocking the EDT. You could then do something like outlined below (my code might not compile 100%, but it should give you an idea of what i mean.
As for your question : just set the animated gif as the JLabel’s icon – and SWING should take care of showing it. As long as your SMS sending code runs on another thread, SWING should happily be able to render the GIF animations without being blocked by the SMS sending code.