Java Reference
In-Depth Information
class
URL
from the
java.net
library. One passes the address as a string in the
constructor. More on accessing the net may be found in Chapter 22. The fol-
lowing application
WebImageFrame
fetches the picture of a pear
pear.png
from
the specified net address and displays it. The file size is 190 kilobytes. Depend-
ing on the bandwidth of the network connection, it can take up to 10 seconds
to load. The application works only if the computer has access to the Internet.
Attempts to access net locations can fail for many reasons, which are beyond
the control of the user. Therefore, the corresponding Java statements are embed-
ded into
try-catch
blocks. This allows the program to continue in case network
access fails.
File:
its/Images/WebImageFrame.java
1.
package
its.Images;
2.
3.
import
its.SimpleFrame.SimpleFrame;
4.
import
java.net.URL;
import
javax.swing.ImageIcon;
5.
import
javax.swing.JLabel;
6.
7.
8.
public class
WebImageFrame
extends
SimpleFrame
{
9.
10.
11.
public
WebImageFrame()
{
12.
13.
URL picURL =
null;
14.
JLabel pictureLabel =
null;
15.
try
16.
{
17.
picURL =
new
URL("http://www.imm.dtu.dk/swingbook/"+
18.
"+HTMLTest/pear.png");
19.
}
20.
catch
(Exception ex)
21.
{System.out.println("Problems in creating URL"+picURL.getPath());}
22.
if
(picURL !=
null
){
23.
ImageIcon picture =
new
ImageIcon(picURL);
24.
pictureLabel =
new
JLabel(picture);
25.
}
26.
else
{
pictureLabel =
new
JLabel("Image not loaded");
27.
}
28.
this.
getContentPane().add(pictureLabel);
29.
pack();
30.
}
31.
32.
33.
public static void
main(String[] args)
Search WWH ::
Custom Search