'My Image aren't correctly display in my JPanel

after i tried many things on my little application, i still have a problem with my image. I create an application who can display the image of a folder but they are flatted when to many of them or cutt off. So i tried to use a JScrollPane to resolve the issue and just have to scrool to get the other images, but it still don't work. If some of you can provide me a little help, thank you. here is my code

 private void placeComponents() {
  imageFrame.getContentPane().setBackground(Color.WHITE);

  Border border = BorderFactory.createEtchedBorder();
  JPanel sidePanel = new JPanel(new GridLayout(0, 1)); {
   JPanel categoriePanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); {
    JPanel categorie = new JPanel(new GridLayout(0, 1)); {
     categoriePanel.add(randomButton);
     categoriePanel.setBorder(border);
    }
    categoriePanel.add(categorie);
   }
   sidePanel.add(categoriePanel);
  }
  JPanel displayPanel = new JPanel(new GridLayout(0, 1)); {
   JPanel imgPanel = new JPanel(new GridLayout(imgList.getImageList().length / 3, 3, 2, 2)); {

    for (BufferedImage i: imgList.getImageList()) {
     JPanel currentImg = new JPanel() {
      @Override
      protected void paintComponent(Graphics g) {
       super.paintComponent(g);

       int width = i.getWidth() * (displayPanel.getWidth() / 2) / i.getWidth();
       int height = i.getHeight() * (displayPanel.getWidth() / 2) / i.getWidth();
       g.drawImage(i, 0, 0, width, height, null);
      }

     };

     imgPanel.add(currentImg);
    }
   }
   scrollPane = new JScrollPane(imgPanel);
   scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
   scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

   displayPanel.add(scrollPane);

  }

  imageFrame.add(sidePanel, BorderLayout.WEST);
  imageFrame.add(displayPanel, BorderLayout.CENTER);

 }

i create a random button on the side and in an other panel i tried to display the image stock in my BufferedImage array. this is the actual result :

resultWhenItsNotWorkingCorrectly

we can see that image are flatted or cut



Solution 1:[1]

Use the size of the component the image is being drawn into:

//  ...
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // use the same minimum rate to avoid distortion
        // and still have the whole image painted
        double ratio = Math.min( (double)getHeight()/i.getHeight(), 
                                 (double)getWidth()/i.getWidth()  );
        int width = (int) (i.getWidth() * ratio);
        int height = (int) (i.getHeight() * ratio);

        g.drawImage(i, 0, 0, width, height, null);
    }
//  ...

This should also work if the frame size is changed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1