Cherple
Cherple

Reputation: 791

How to resize images in JScrollPane as frame resizes

I need to develop an image gallery of sorts, where I can display images in a JFrame, and I can scroll and double click to expand to full screen etc. I was able to display the images the way I want it, but when I resize the JFrame, the images gets cut off as there is no horizontal scroll.

Is there a way where I can have have vertical scroll and when frame resizes, the panel within will resize to fit horizontally?

try {
    
    BufferedImage readImage = ImageIO.read(new File("myFile.png"));
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(readImage, "png", bos);
    byte[] data = bos.toByteArray();
    BufferedImage image = ImageIO.read(bis);
    
    JPanel imagePanel = new JPanel();
    imagePanel.setLayout(new GridLayout(0,2,5,5));
    for (int x=0;x<8;++x){
        JLabel l = new JLabel(new ImageIcon(image));
        imagePanel.add(l);
    }
    
    JScrollPane scrollPane = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    
    JFrame frame = new JFrame();
    frame.add(scrollPane);
    //frame.add(imagePanel); //This will work as i intended it to be, but there is no vertical scroll
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
} catch (IOException e) {
    e.printStackTrace();
}

Edit:

A visual example is shown below. When the frame resizes, the images get cropped, what I would like instead are for the images within the JScrollPane to resize so that it could all fit horizontally, while at the same time maintaining the vertical scroll.

cropped images

Edit2:

Using StretchIcon, I was able to achieve having the images resize dynamically, but this introduced another issue where there are huge spaces in between the images as I resize.

large gaps

Upvotes: 1

Views: 52

Answers (0)

Related Questions