【Java】java學習筆記:【從網路擷取映像資源】實現__Java

來源:互聯網
上載者:User

JAVA訪問網路資源

下面將通過JAVA的URL類來從網上得到映像

//從網路擷取映像資源//InternetAccess.javaimport java.awt.*;//import java.awt.event.*;import javax.swing.*;import java.net.*;public class InternetAccess {  public static void main(String[] args)  {   ImageFrame frame=new ImageFrame();     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //frame.show();//show方法已經過時   frame.setVisible(true);  }}class ImageFrame extends JFrame{  /**  *   */ private static final long serialVersionUID = 1L;public static final int WIDTH=300;  public static final int HEIGHT=120;    public ImageFrame()  {    setTitle("InternetAccess");    setSize(WIDTH,HEIGHT);        ImagePanel panel=new ImagePanel();    Container contentPane=getContentPane();    contentPane.add(panel);  }  }class ImagePanel extends JPanel{  /**  *   */  private static final long serialVersionUID = 1L;  private Image image;  URL url;    public ImagePanel()  {   try   {    //指定要擷取的資源的URL    url=new URL("http://www.kklinux.com/uploads/090313/2_204213_1.jpg");   }   catch(MalformedURLException e)   {       }   //擷取指定URL上的映像   image=Toolkit.getDefaultToolkit().getImage(url);  }    public void paintComponent(Graphics g)  {   super.paintComponent(g);      int imageWidth=image.getWidth(this);   int imageHeight=image.getHeight(this);      //在視窗中顯示映像   g.drawImage(image, 0, 0, imageWidth, imageHeight, null);   g.drawImage(image,0,0,null);   //顯示字串   g.drawString("正在下載映像...", 100, 80);  }}

運行結果:

 

當顯示視窗時,先顯示字串,然後才顯示映像。這個結果和我們的程式編寫次序相反。原因在於JAVA使用了多線程機制。因為下載映像是比較費時的操作,而顯示字串是本地操作,如果不適用多線程,那麼必須先等待映像下載完畢,然後字串才能顯示,這樣在等待下載映像的過程中,使用者恐怕不知道程式現在在做什麼。因此採用多線程機制,程式不必一直等待下載操作,而是能夠“同時”運行多個操作,這能夠使得程式具有很好的介面友好性。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.