如何在更改 JLabel 大小时动态缩放图像

How to dynamically scale an image when changing the size of the JLabel

我已将图像读入 JLabel 并将图像缩放到 JLabel 的大小,如下所示:

File file = new File ("C:/Users/Me/Desktop/TestImages/test.jpg");
BufferedImage image = ImageIO.read(file);

Image scaledImage = image.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
label.setIcon(new ImageIcon(scaledImage));

我正在使用提供的 GroupLayout 并将水平轴和垂直轴设置为 "Auto-Resizable"(通过设计视图),以便 JLabel 的大小自动调整每当我更改 window 大小时,JFrame 的大小。

现在我想调整图像的大小和 JLabel 的大小,麻烦就来了。我添加了一个事件处理程序来响应调整 JFrame 的大小,如下所示:

addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                addScaledImage(); // executes the lines above 
            }
        });

这在理论上可行,但速度极慢。所以我尝试将事件处理程序添加到 JLabel 而不是 JFrame,但这导致了另一个问题:图像不断扩展而没有执行任何操作。然后我用 JScrollPane 围绕 JLabel,并将事件处理程序添加到 JScrollPane。只要我正在扩展 JFrame 的大小,这就有效。但是,当我减小 windows 大小时,图像并没有缩小,而是保持不变。

  1. 是否有更优雅的方法来集成事件处理程序(可能没有 JScrollPane 的帮助)?

  2. 如何使我的 image/JLabel 与任何调整大小事件一起自动调整大小(增加和减小 JFrame 的大小)?另一种方法(例如另一种 LayoutManager)可能更适合这个吗?

  3. 此外,如果我想保持图像的高宽比,是否有为此指定的缩放方法?

I'd like to adjust the size of the image together with the size of the JLabel

可以使用Stretch Icon。当标签尺寸改变时,它会自动缩放。适用于任何可以显示图标的组件。

Then I surrounded the JLabel with a JScrollPane

However, when I reduce the windows size, the image is not being reduced in size but instead stays the same

您不应该使用 JScrollPane。当滚动窗格缩小时,添加到滚动窗格的组件的大小不会改变。而是显示滚动条。

I'm using the provided GroupLayout and set the horizontal and vertical axes to "Auto-Resizable

我不会使用 IDE 来生成布局代码,我也不会使用 GroupLayout,因为它对于这么简单的东西来说过于复杂。

只需将标签(使用 StretchIcon)添加到框架中。默认情况下,框架使用 BorderLayout,它将自动调整添加到 BorderLayout 中心的任何组件的大小。