简体   繁体   中英

Set an Image to a ScrollPane and scale it by width

I want to set an image to a ScrollPane (at a Panel) and set the Image to the width of the Panel.

I use a JLabel to put the image on and set the label into a ScrollPane, because the Image can be larger.

I want to scale the Image to the width of the Panel, the height should be the same proprtion.

Here is my code (where pInfo is my JPanel to add the image to):

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

The problem is, that the ScrollPane gets a vertical ScrollBar that overlays a bit of the Image. Resizing the Image (by ImgSclr or Graphic2D) doens't work, because the ScrollPane is then shorter too. Also tried to add the label and set the bounds of the ScrollPane after this, but didn't work either.

在此处输入图片说明

Is there a way of doing this?

Check out:

  1. Scrollable Panel . This will allow you to force the width of the component add to the scrollpane to be the width of the viewport.

  2. Stretch Icon . This will allow the Icon to be resized to fill the space available to it. You can keep the same ratio.

So you should be able to just add your JLabel to the JScrollPane and the image should be resized automatically as the size of the scrollpane is changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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