如何使图像大小适合JFrame大小?

时间:2012-10-23 20:08:58

标签: java image swing jframe jpanel

JPanel中有一个JFrame。我在JPanel上加了一张图片,但它只显示了图片的一部分:这是代码的一部分,我做了它:

JPanel panelImg = new JPanel()
{
    public void paintComponent(Graphics g)
    {
        Image img = new ImageIcon("Welcome.png").getImage();
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
        g.drawImage(img, 0, 0, null);
    }
};
mainFrame.add(panelImg);

所以这就是它的样子:

Picture 1

完整的图片如下所示:

enter image description here

有没有办法将图片缩放到JFrame的大小?提前致谢

5 个答案:

答案 0 :(得分:14)

您希望缩放到目标容器的drawImage()。有关替代方案,请参阅引用文章here。例如,

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

答案 1 :(得分:13)

首先,我不会在paintComponent方法中加载图像,这种方法是重复调用(有时连续快速调用),你不想做任何需要时间的事情。不必要地执行或消耗资源

查看Java: maintaining aspect ratio of JPanel background image有关填充/拟合图像到特定区域的建议

答案 2 :(得分:2)

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {

    Image image;

    public void setBackground(Image image) {
        this.image = image;
    }

    @Override
    public void paintComponent(Graphics G) {
        super.paintComponent(G);
        G.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
    }

}

然后使用ImagePanel对象方法SetBackground,如

imagePanel1.SetBackGround(ImageIO.read(new File("extensions/images/background.jpg")));

答案 3 :(得分:1)

很容易。按照这个例子,

public class BasePanel extends JPanel {

ImageIcon backImage;
public BasePanel() {
    backImage = new ImageIcon("src/images/welcome.png");
}

@Override
protected void paintComponent(Graphics g) {
    BufferedImage scaledImage = getScaledImage();
    super.paintComponent(g);
    g.drawImage(scaledImage, 0, 0, null);
}

private BufferedImage getScaledImage(){
    BufferedImage image = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) image.createGraphics();
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
    g2d.drawImage(backImage.getImage(), 0, 0,getWidth(),getHeight(), null);

    return image;
}

}

答案 4 :(得分:0)

你可以试试这个:

Image img = new ImageIcon(ImageIO.read(new File("welcome.png"))
                               .getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH)));