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使用了多線程機制。因為下載映像是比較費時的操作,而顯示字串是本地操作,如果不適用多線程,那麼必須先等待映像下載完畢,然後字串才能顯示,這樣在等待下載映像的過程中,使用者恐怕不知道程式現在在做什麼。因此採用多線程機制,程式不必一直等待下載操作,而是能夠“同時”運行多個操作,這能夠使得程式具有很好的介面友好性。