如何使BMP填充JPanel

时间:2012-08-17 15:16:15

标签: java image swing

如何让BMP填满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){

    }



}

1 个答案:

答案 0 :(得分:2)

您需要回答的第一个问题是,您希望保持BMP的宽高比吗?

如果不这样做,那就像

一样简单
Image scaled = image.getScaledInstance(getWidth() - 1, getHeight() - 1, Image.SCALE_SMOOTH);

如果没有,那么你需要问自己。我想“填充”或“适合”图像吗?填充将允许图像溢出面板,但将完全填充它,适合将确保整个图像适合面板,但可能留下间隙。

阅读此answer,这是对类似问题的回应