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

來源:互聯網
上載者:User

JAVA訪問網路資源

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

 

 1 //從網路擷取映像資源
2 //InternetAccess.java
3 import java.awt.*;
4 //import java.awt.event.*;
5 import javax.swing.*;
6 import java.net.*;
7
8 public class InternetAccess
9 {
10 public static void main(String[] args)
11 {
12 ImageFrame frame=new ImageFrame();
13 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14 //frame.show();//show方法已經過時
15 frame.setVisible(true);
16 }
17 }
18
19 class ImageFrame extends JFrame
20 {
21 /**
22 *
23 */
24 private static final long serialVersionUID = 1L;
25 public static final int WIDTH=300;
26 public static final int HEIGHT=120;
27
28 public ImageFrame()
29 {
30 setTitle("InternetAccess");
31 setSize(WIDTH,HEIGHT);
32
33 ImagePanel panel=new ImagePanel();
34 Container contentPane=getContentPane();
35 contentPane.add(panel);
36 }
37 }
38
39 class ImagePanel extends JPanel
40 {
41 /**
42 *
43 */
44 private static final long serialVersionUID = 1L;
45 private Image image;
46 URL url;
47
48 public ImagePanel()
49 {
50 try
51 {
52 //指定要擷取的資源的URL
53 url=new URL("http://www.kklinux.com/uploads/090313/2_204213_1.jpg");
54 }
55 catch(MalformedURLException e)
56 {
57
58 }
59 //擷取指定URL上的映像
60 image=Toolkit.getDefaultToolkit().getImage(url);
61 }
62
63 public void paintComponent(Graphics g)
64 {
65 super.paintComponent(g);
66
67 int imageWidth=image.getWidth(this);
68 int imageHeight=image.getHeight(this);
69
70 //在視窗中顯示映像
71 g.drawImage(image, 0, 0, imageWidth, imageHeight, null);
72 g.drawImage(image,0,0,null);
73 //顯示字串
74 g.drawString("正在下載映像...", 100, 80);
75 }
76 }

運行結果:

 

當顯示視窗時,先顯示字串,然後才顯示映像。這個結果和我們的程式編寫次序相反。原因在於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.