2012-09-26 63 views
0

我嘗試了一個HTTP鏈接,使用一個圖形用戶界面下載時下載開始下載按鈕將開始下載,下載正在工作,但標籤沒有改變,當開始下載時在ActionListener中聲明。請幫幫我。JAVA:JLabel不會改變事件

這裏的時候下載的開始及結束時的代碼

標籤應該改變。

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); 
     } 
    }); 
} 

}

回答

1

您正在嘗試運行從事件指派線程進行下載,從而導致你的GUI凍結,而正在執行的任務。

看看SwingWorker執行下載任務作爲後臺線程。你actionPerformed方法應該是這樣的:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
    jLabel1.setText("Download Started"); 
    SwingWorker sw = new SwingWorker() { 
      public Object doInBackground(){ 
       try { 
        // ... 
        // Do the whole download thing 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

       jLabel1.setText("Completed"); 
       return null; 
      } 
     }; 
    sw.execute(); 
} 

注:請確保您不要吞嚥異常在此捕獲,否則你將無法看到是否有任何錯誤發生。

+0

非常感謝,我甚至都不知道我做錯了什麼,關於SwingWorker ...是一個很棒的Java時代的新手!現在,讓我進入進度條 – rohitpal

+0

什麼是SwingWorker等同於用於java的SWT? – rohitpal

0

您在Event Dispatch Thread下運行的下載是錯誤的。這阻止EDT線程執行除下載之外的任何操作。

您應該在單獨的線程中進行下載,並且標籤將開始更新。