如何使BMP填充JPanel [英] How to make BMP fills the JPanel

查看:105
本文介绍了如何使BMP填充JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让BMP填充JPanel?

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){

    }



}


推荐答案

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

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

如果不这样做,那就像

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

这篇关于如何使BMP填充JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆