Search code examples
javaapplet

How to dynamically resize applet components when the window changed?


i tried the following code to display an image on applet, but when i tried to change the size pf the applet window the loaded image doesn't resized, why that happen?

import java.applet.*;
import java.awt.*;

public class ImageViewer extends Applet
{
    Image image;
    int imageX, imageY;
    MediaTracker mt;

    public void init()
    {
        showStatus("Getting image...");
        mt = new MediaTracker(this);
        image = getImage(getDocumentBase(), "fruits.jpg");
        mt.addImage(image, 0);
    }

    public void start()
    {
        showStatus("Loading image...");
        try
        {
            mt.waitForAll();
        } catch(Exception e)
        {
            e.printStackTrace();
        }
        while(!mt.checkAll(true)){}
        imageX = image.getWidth(this);
        imageY = image.getHeight(this);
        showStatus("Resizing Applet image size: " + imageX + "x" + imageY);
        resize(imageX, imageY);
    }

    public void paint(Graphics g)
    {
        showStatus("Drawing image...");
        g.drawImage(image, 0, 0, this);
    }

}

Solution

  • The image doesn't resize as you're using the Graphics.drawImage method which uses the images own size instead of the size of the Applet container

    g.drawImage(image, 0, 0, this);
    

    You could replace this with

    g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    

    Also don't forget to call

    super.paint(g);
    

    to draw any child components including the container background.


    BTW: java.awt.Applet is something of a relic now, having been replaced by JApplet. This is part of Java Swing which uses lightweight resources and has many more features.