Search code examples
javaeclipsecanvasappletclip

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 painted, it should

  1. fill its whole area with red
  2. 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.

enter image description here

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 of setSize() both in MyApplet and MyCanvas just in case the position was offset toward the top-left. This just shifted the circle -- the clip persisted.

Am I missing something?


Solution

  • 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:

    1. Right-click the root folder of your applet in the Package view
    2. Select Run As... -> Run Configurations...
    3. Click the Parameters tab
    4. Change Width and Height fields as required.