Internet Computing: CSM02
Lab. Session 4: Applets
In this lab class, you will use a different way of invoking behaviour in a Java application. Instead of using the “main” method, we will run an application as an Applet in a web browser. In this case, we will “paint” the application in the browser window.
Let’s start with a very simple applet.
First, download the file “Venus.gif” from: http://www.computing.surrey.ac.uk/courses/csm15/GIF/
Now, you need to create a file called “HelloFromVenus.java”
Enter in the following code:
/*
* Copyright (c) 1999-2002, Xiaoping Jia.
* All Rights Reserved.
*/
import java.awt.*;
import java.applet.Applet;
/**
* A simple Java applet. It displays the greeting message "Hello from Venus!"
* graphically.
* It consists of a text message and an image of the planet Venus.
*/
public class HelloFromVenus extends Applet {
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(Color.black);
g.fillRect(0,0,d.width,d.height);
g.setFont(new Font("Helvetica", Font.BOLD, 24));
g.setColor(new Color(255, 215, 0)); // gold color
g.drawString("Hello From Venus!", 40, 25);
g.drawImage(getImage(getCodeBase(), "Venus.gif"),
20, 60, this);
}
}
Note that there is no “main” method. Instead, we have a “paint” method. When you are writing Applets for use on the internet, you will always need to include a “paint” method. The paint method is invoked when the applet is initially loaded in the browser.
Compile the file. Correct any errors of there are any to make sure you have a cleanly compiled file.
Now you need to create a web page to load this Applet. Save the following source in a file called, for example, HelloDemo.html (although you don’t need to use this name):
Object-Oriented Software Development Using Java | HelloFromVenus Applet
Here is the Hello From Venus Applet
Venus photo courtesy of NASA.
Dostları ilə paylaş: |