Du kan ikke bare eksekvere en applet. Den skal indlejres i en HTML side og så startes i en browser eller appletvieweren.
RandomApplet.java:
import javax.swing.JApplet;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
public class RandomApplet extends JApplet {
private JTextField textField;
private JButton button;
private Random random;
public void init() {
getContentPane().setLayout(null);
random = new Random();
textField = new JTextField();
button = new JButton("New random");
button.setSize(button.getPreferredSize());
textField.setSize(getSize().width - button.getSize().width - 15, textField.getPreferredSize().height);
textField.setLocation(5, 5);
button.setLocation(textField.getSize().width + 10, button.getSize().height/2 - button.getSize().height / 2 + button.getLocation().y);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("" + Math.abs(random.nextInt() % 100));
}
});
add(textField);
add(button);
}
}
test.html:
<html>
<body>
<center>
<applet code="RandomApplet" width="200" height="75">
</applet>
</center>
</body>
</html>
Start så med:
robert-desktop:~/code/test $ javac RandomApplet.java
robert-desktop:~/code/test $ appletviewer test.html
...eller bare åben test.html i en web browser.