将图像设置为ScrollPane并按宽度缩放

问题描述 投票:0回答:1

我想将图像设置为ScrollPane(在Panel中)并将Image设置为Panel的宽度。

我使用JLabel打开图像并将标签设置为ScrollPane,因为Image可以更大。

我想将Image缩放到Panel的宽度,高度应该是相同的proprtion。

这是我的代码(其中pInfo是我的JPanel添加图像):

BufferedImage image;
JLabel picLabel = new JLabel();
int w = pInfo.getWidth();

pInfo.removeAll();
try {
    image = ImageIO.read(getClass().getResourceAsStream("/Matrix/ausstoepseln.jpg"));
    picLabel = new JLabel(new ImageIcon(image));                                    
} catch (IOException e1) {
    e1.printStackTrace();
} 

JScrollPane scrollP = new JScrollPane (picLabel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollP.setBorder(new TitledBorder ( new EtchedBorder (), "Info" ));
pInfo.add(scrollP);

问题是,ScrollPane得到一个垂直的ScrollBar,它覆盖了一些Image。调整图像大小(通过ImgSclr或Graphic2D)不起作用,因为ScrollPane也会更短。此后尝试添加标签并设置ScrollPane的边界,但也无法正常工作。

enter image description here

有办法做到这一点吗?

java image swing
1个回答
0
投票

查看:

  1. Scrollable Panel。这将允许您强制组件的宽度添加到滚动窗格作为视口的宽度。
  2. Stretch Icon。这将允许调整Icon的大小以填充可用空间。你可以保持相同的比例。

因此,您应该能够将JLabel添加到JScrollPane,并且应该在更改滚动窗格的大小时自动调整图像大小。

© www.soinside.com 2019 - 2024. All rights reserved.