简体   繁体   English

我可以使JLabel的图标图像可调整大小吗?

[英]Can I make a JLabel with an icon image resizeable?

Just like we can resize a JFrame I'd like to show an image on a frame. 就像我们可以调整JFrame大小一样,我想在框架上显示图像。 I'd like to be it resizeable so when I resize the image should be resized. 我希望它可以调整大小,所以当我调整大小,图像应该重新调整大小。

How could I do this? 我该怎么办?

try {
    myPicture = ImageIO.read(f);
    picLabel.setIcon(new ImageIcon(myPicture));
    panel.add(picLabel);
} catch (IOException e) {
    e.printStackTrace();
}

I added the label (with the image) to a JPanel and the panel is added to the frame. 我将标签(带有图像)添加到了JPanel ,并将面板添加到了框架。

ImageIcons are always resizeable. ImageIcons始终可调整大小。 Try converting it to an image , resizing it, convert it back to an ImageIcon , and then reapplying it (of course do this when you want to resize it). 尝试将其转换为image ,调整其大小,将其转换回ImageIcon ,然后重新应用它(当然,要调整其大小时可以这样做)。

Image myScaledPicture = myPicture.getImage().getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
picLabel.setIcon(new ImageIcon(myScaledPicture);

More info here: How to resize JLabel ImageIcon? 更多信息在这里: 如何调整JLabel ImageIcon的大小?

You can use the Stretch Icon . 您可以使用“ 拉伸图标”

It can be used in any component that can paint an Icon and the image will scale as the component is resized. 它可以在可以绘制图标的任何组件中使用,并且随着组件调整大小,图像将缩放。

It is reusable code so you don't have to do custom painting all the time. 它是可重用的代码,因此您不必一直进行自定义绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM