Reputation: 4195
I am trying to set up a simple JApplet
using IntelliJ. I have a class called Square
and a HTML file which should make it work, but I keep getting a ClassNotFoundException
.
import javax.swing.*;
import java.awt.*;
public class Square extends JApplet {
int size = 40;
public void init() {
JButton butSmall = new JButton("Small");
JButton butMedium = new JButton("Medium");
JButton butLarge = new JButton("Large");
JButton butMessage = new JButton("Say Hi!");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(butSmall);
butPanel.add(butMedium);
butPanel.add(butLarge);
butPanel.add(butMessage);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
}
class SquarePanel extends JPanel {
Square theApplet;
SquarePanel(Square app) {
theApplet = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(20, 20, theApplet.size, theApplet.size);
}
}
and the HTML file
<HTML>
<APPLET CODE="Square.class"> WIDTH=400 HEIGHT=200>
</APPLET>
</HTML>
This is the folder structure. I've tried lots of different combos and names and <> delimiters but I can't get it to open properly.
Upvotes: 0
Views: 442
Reputation: 205805
The problem is that the applet container, typically a browser, has been told where to find the class Square
but not the class SquarePanel
. You can do either of two things:
Enclose your classes in a JAR and specify the archive
name in your <APPLET\>
tag, as shown here.
Nest SquarePanel
in Square
, as shown below for illustration purposes.
A JAR is the preferred approach, but also consider a hybrid for more flexible testing and deployment. For convenient appletviewer
testing, the tag is included in a comment, as shown here.
Command line:
$ appletviewer Square.java
Code, as tested:
// <applet code='Square' width='400' height='200'></applet>
import javax.swing.*;
import java.awt.*;
public class Square extends JApplet {
int size = 40;
public void init() {
JButton butSmall = new JButton("Small");
JButton butMedium = new JButton("Medium");
JButton butLarge = new JButton("Large");
JButton butMessage = new JButton("Say Hi!");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(butSmall);
butPanel.add(butMedium);
butPanel.add(butLarge);
butPanel.add(butMessage);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private static class SquarePanel extends JPanel {
Square theApplet;
SquarePanel(Square app) {
theApplet = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(20, 20, theApplet.size, theApplet.size);
}
}
}
Upvotes: 2