Java Applet painting clips to [195,200] despite resize
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?
In the first line of your init put this:
setLayout(new GridLayout(1,1));
This will cause your canvas to take up all the space of your applet.
You want to be calling setPreferredSize
and this explains the differences
Finally found it!
The environment that Eclipse provides to Applets is by default configured to have size 200, 200. All painting clips to this area unless the default Run Configuration is changed.
This can be done as follows:
- Right-click the root folder of your applet in the Package view
- Select Run As... -> Run Configurations...
- Click the Parameters tab
- Change Width and Height fields as required.
精彩评论