I've uploaded several examples of applets here
An applet is a Java program that is loaded and executed within an HTML page.
Write your class so it extends JApplet
public class HelloWorld extends JApplet {
...
}
page.html
)
as<applet code=AppletWorld.class width="200" height="200">
</applet>
appletviewer page.html
init
: run once. Intended for initializations
start
: run one or more times. Automatically called after init
, and
called when the user returns to the page containing the applet.
stop
: run one or more times. Automatically called when the user moves away from the
page containing the applet. Can also be called by the applet code.
destroy
: called once when the browser shuts down normally.
paint
: called automatically. Used to draw the screen (import JApplet
and Graphics
to get paint to work.
repaint
: like paint, except it's used when the window (that has the applet)
regains focus.
paint
is useful
Copy and paste, run in IDE and display
import javax.swing.JApplet;
import java.awt.Graphics;
public class HelloWorld extends JApplet {
public void paint(Graphics g) {
g.drawRect(10, 10, getSize().width - 20, getSize().height - 20);
g.drawString("Hello world!", 50, 55);
}
}
Here's an example of an html page with an applet in it: click here
Here's another code example to copy and paste taken from java.sun.com
tutorials
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
public class ApptoAppl extends Applet
implements ActionListener {
JLabel text;
JButton button;
JPanel panel;
private boolean _clickMeMode = true;
public void init(){
setLayout(new BorderLayout(1, 2));
setBackground(Color.white);
text = new JLabel("I'm a Simple Program");
button = new JButton("Click Me");
button.addActionListener(this);
add("Center", text);
add("South", button);
}
public void start(){
System.out.println("Applet starting.");
}
public void stop(){
System.out.println("Applet stopping.");
}
public void destroy(){
System.out.println("Destroy method called.");
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if (_clickMeMode) {
text.setText("Button Clicked");
button.setText("Click Again");
_clickMeMode = false;
} else {
text.setText("I'm a Simple Program");
button.setText("Click Me");
_clickMeMode = true;
}
}
}