package net.codejava.applet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class QuickApplet extends JApplet {
private JButton button;
public void init() {
button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(QuickApplet.this,
"Hello! I am an applet!");
}
});
System.out.println("APPLET IS INITIALIZED");
}
public void start() {
getContentPane().add(button);
System.out.println("APPLET IS STARTED");
}
public void stop() {
System.out.println("APPLET IS STOPPED");
}
public void destroy() {
System.out.println("APPLET IS DESTROYED");
}
}Place the QuickApplet.java file under the directory structure: src\net\codejava\applet javac -d build src\net\codejava\applet\QuickApplet.java
The compiled .class files will be placed under the build directory. Type the following command to package the applet (not that there is a period at the end):jar cvf QuickApplet.jar -C build .
That will add all classes in the build directory to a single jar file named QuickApplet.jar.<html> <head> <title>Quick Start Java Applet</title> </head> <body> <center> <applet code="net.codejava.applet.QuickApplet.class" archive="QuickApplet.jar" width="125" height="125" > </applet> </center> </body> </html>We use to embed the applet in the HTML page. See the article How to show Java applet in HTML page for more details about using the <applet> tag.
Click on the button, a message dialog appears:
Note that a dialog message created by Java applet has an exclamation mark in the upper right corner.And following is logging information from Java applet console:
Download the quick applet project in the attachment section.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.