Java Reference
In-Depth Information
This applet accepts a Fahrenheit temperature from the user and converts it into the
corresponding Celsius temperature. Following the convention established in earlier
examples, the associated minimal HTML fi le (not shown below) will have the same
name as the applet, but with a suffi x of .html .
import java.awt.*;
import javax.swing.*;
public class FahrToCelsius extends JApplet
private String fahrString;
private fl oat fahrTemp, celsiusTemp;
public void init()
//Prompt user for a temperature and
//accept value…
fahrString = JOptionPane.showInputDialog(
"Enter temperature in degrees Fahrenheit");
//Convert string into a fl oat…
fahrTemp = Float.parseFloat(fahrString);
//Carry out the conversion…
celsiusTemp = (fahrTemp-32)*5/9;
//Set up the response within a JLabel
JLabel message = new JLabel(
"Temperature in degrees Celsius: "
+ celsiusTemp,JLabel.CENTER);
//Add the above label to the applet…
Sample output for Chrome is shown in Figs. 12.6 and 12.7 .
Using Images in Applets
As noted in the previous chapter, classes Image (package java.awt ) and ImageIcon
(package javax.swing ) are both used for holding and manipulating images. Either
may be used on its own, but ImageIcon is particularly useful for loading an image
into an application from the current directory. In theory, ImageIcon should be just
as useful in applets. However, there is a problem that considerably restricts the
usefulness of ImageIcon s in applets. Since explanation of this problem involves a
Search WWH ::

Custom Search