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

2022-01-24 00:00:00 image java swing jpanel jframe

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

I have a JPanel into a JFrame. I loaded a picture on the JPanel but its shown just a part of the picture: This is the part of the code where i did it:

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

这就是它的样子:

全图是这样的:

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

Is there a way to scale the picture to the JFrames size? Thanks in advance

推荐答案

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

First of all, I wouldn't be loading the image inside the paintComponent method, this method is call repeatedly (and some times in quick succession), you don't want to do anything that takes time to execute or consumes resources unnecessarily

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

Check out Java: maintaining aspect ratio of JPanel background image for suggestions on filling/fitting images to a given area

相关文章