Intention
I have a java.applet.Applet
subclass MyApplet
with a java.awt.Canvas
subclass MyCanvas
added to it.
My code changes the size of MyApplet
to new Dimension(600,400)
and changes the size of MyCanvas
to match.
When MyCanvas
is paint
ed, it should
- fill its whole area with red
- draw a blue circle of width 300 and height 300.
Problem
Instead (when run as a Java Applet from Eclipse), the paint of MyCanvas
clips to a far smaller area than 600,400 (I measured it to be 195,200) even though MyApplet
resizes correctly. This is what it looks like.
The printouts are OK too -- see bottom of post.
Code
This is my code:
import java.applet.Applet;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
public class MyApplet extends Applet {
Canvas mainCanvas;
public void init() {
// Set the size of the applet
setSize(600, 400);
// Print dimensions
System.out.println("Applet dimensions: " + getSize());
// Make a canvas with the same sizes as this applet
mainCanvas = new MyCanvas(getWidth(), getHeight());
add(mainCanvas);
}
public class MyCanvas extends Canvas {
public MyCanvas(int w, int h) {
setSize(w, h);
System.out.println("Canvas dimensions: " + getSize());
}
public void paint(Graphics g) {
g.setColor(Color.RED);
System.out.println("Canvas dimensions when painting: " + getSize());
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
Printouts
It produces the following printout:
Applet dimensions: java.awt.Dimension[width=600,height=400]
Canvas dimensions: java.awt.Dimension[width=600,height=400]
Canvas dimensions when painting: java.awt.Dimension[width=600,height=400]
Canvas dimensions when painting: java.awt.Dimension[width=600,height=400]
The sizes are correct throughout!
Attempted solutions
- I tried
setBounds()
instead ofsetSize()
both inMyApplet
andMyCanvas
just in case the position was offset toward the top-left. This just shifted the circle -- the clip persisted.
Am I missing something?