Java Access network resources
The following is a Java URL class to get images from the Web
Acquiring image resources from the network//internetaccess.java import 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 method is obsolete frame.setvisible (true); Class ImageFrame extends JFrame {/** * */private static final long serialversionuid = 1L; public static fin
Al 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 {//Specify the URL url=new URL for the resource to get ("http://www.kklinux.com/uploads/090313/2_204213_1.jpg ");
The catch (Malformedurlexception e) {}//Gets the image Image=toolkit.getdefaulttoolkit (). GetImage (URL) on the specified URL;
public void Paintcomponent (Graphics g) {super.paintcomponent (g);
int Imagewidth=image.getwidth (this);
int Imageheight=image.getheight (this);
Displays the image g.drawimage in the window (image, 0, 0, imagewidth, imageheight, NULL);
G.drawimage (Image,0,0,null);
Display string g.drawstring ("Downloading images ...", 100, 80); }
}
Run result :
When the window is displayed, the string is displayed before the image is displayed. The result is the reverse of our programming order. The reason is that Java uses multithreaded mechanisms. Because downloading images is a time-consuming operation, and the display string is a local operation, if multiple threads are not applicable, you must wait for the image to be downloaded before the string can be displayed, so that in the process of waiting for the download image, the user may not know what the program is doing now. Therefore, the use of multithreaded mechanism, the program does not have to wait for the download operation, but can "simultaneously" run multiple operations, which can make the program has a good interface friendly.