9

我有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);

所以这就是它的样子:

图片1

完整的图片如下所示:

在此处输入图像描述

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

4

5 回答 5

13

您希望drawImage()扩展至目标容器。有关替代方案,请参阅此处引用的文章。例如,

g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
于 2012-10-23T20:11:38.033 回答
13

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

查看Java:维护 JPanel 背景图像的纵横比以获取有关将图像填充/拟合到给定区域的建议

于 2012-10-23T20:17:24.083 回答
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")));
于 2013-07-03T12:19:25.683 回答
1

你可以试试这个:

Image img = new ImageIcon(ImageIO.read(new File("welcome.png"))
                               .getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH)));
于 2014-06-22T15:15:01.183 回答
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;
}

}
于 2016-01-01T04:34:59.943 回答