3

How to make that BMP will fill the JPanel?

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BMPPanel extends JPanel {


    String sciezka;
    Image image;
    int skala;
    int rozdzielczosc;
    Dimension d;
    public static int NORMALNA = 0, MALA = 1;

    public BMPPanel(String sciezka, int skala, int rozdzielczosc) {
        this.sciezka = sciezka;
        this.skala = skala;
        this.rozdzielczosc  = rozdzielczosc;
        super.setMaximumSize(d);
        this.d = new Dimension(400,400);
        this.go();
    }
    public BMPPanel(String sciezka, int skala) {
        this(sciezka,skala,200);
    }


    public void go() {
        try {
            File input = new File(sciezka);
            image = ImageIO.read(input);
        } catch (IOException e) {
            e.printStackTrace();
        }



        setPreferredSize(new Dimension(image.getWidth(null),
                image.getHeight(null)));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponents(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(image, 0, 0, this);
    }

    @Override 
    public void setMaximumSize(Dimension d){

    }



}
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • Hopefully this [answer](http://stackoverflow.com/a/11372350/1057230) might can help you in this direction :-) – nIcE cOw Aug 18 '12 at 18:16

1 Answers1

2

The first question you need to answer, is do you wish to maintain the aspect ratio of the BMP?

If you don't then it's as simple as

Image scaled = image.getScaledInstance(getWidth() - 1, getHeight() - 1, Image.SCALE_SMOOTH);

If not, then you need to ask your self. Do I want to "fill" or "fit" the image. Filling will allow the image to overflow the panel, but will completely fill it, fit will make sure the entire image will fit into the panel, but may leave gaps.

Have a read of this answer which is in response to a similar question

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366