Search code examples
javajapplet

Background Image for Applet and Fill in Applet


I am setting an Image as a background for my JApplet and using a resize method to fill the Image into the JApplet background. I am currently using

Image background;
public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(background, 0, 0, this);
}

public void init() {
    // TODO start asynchronous download of heavy resources
    background=resize(new ImageIcon(getClass().getResource("/org/me/pd/resources/music.png")),this.getWidth(),this.getHeight()).getImage();
    this.setLayout(new GridLayout(6,6));
    //Create();
}

This is my resize method

public ImageIcon resize(ImageIcon icon, int width, int height)
{
    BufferedImage converted = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics g = converted.createGraphics();
    icon.paintIcon(null, g, 0,0);
    g.dispose();
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
    Graphics2D g2d = (Graphics2D) bi.createGraphics();
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
    g2d.drawImage(converted, 0, 0, width, height, null);
    g2d.dispose();
    ImageIcon correct=new ImageIcon(bi);
    return correct;
}

This works initially when the Applet is loaded and fills the Image but When the applet is maximised, the Image doesn't Maximise with the Applet. It shows stays how it was before maximising.

What am i doing wrong?


Solution

  • There is no need to rescale the Icon.

    Instead you just let the painting method do this for you:

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

    However, you should not be doing this by overriding the paint() method of the applet.

    Instead you should be overriding the paintComponent() method of a JPanel and add the panel to your applet. Then you pane will become the content pane for the applet. You would then set the layout of the panel to be a BorderLayout so it behaves exactly like the default content pane.