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