简体   繁体   中英

Resize image so that it fits JPanel grid

I have a JPanel with grid layout of (5 , 7 ) , 5 rows , 7 columns.

When i try to add images to a grid panel

    Img = new ImageIcon("ImagePath");
    JLabel Label = new JLabel(Img);
    add(picLabel);

It appears the image is too large for my grid panel , and only a small portion of the image is shown on the grid panel.

How do i add an image to the grid so that the images resizes to the grid size.???

Don't use a JLabel and ImageIcon. Instead, I'd

  • Create a class that extends JPanel
  • Override its paintComponent(Graphics g) method
  • Remember to call the super's method in my override
  • Give it a BufferedImage field, say called image
  • Pass the image into the class via a constructor or setter parameter, or both.
  • Call the g.drawImage(image,....) overload that allows for re-sizing of the image so that it fills the JPanel.

Links:

Check out this overload:

public abstract boolean drawImage(Image img,
            int x,
            int y,
            int width,
            int height,
            ImageObserver observer)

or this one:

public abstract boolean drawImage(Image img,
            int dx1,
            int dy1,
            int dx2,
            int dy2,
            int sx1,
            int sy1,
            int sx2,
            int sy2,
            ImageObserver observer) 

Edit
For example,

// big warning: code not compiled nor tested
public class ImagePanel extends JPanel {
  private BufferedImage image;

  public ImagePanel(BufferedImage image) {
    this.image = image;
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (image != null) {
      g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }
  }
}

How do i add an image to the grid so that the images resizes to the grid size.???

Check out Darryl's Stretch Icon .

It will dynamically resize itself to fill the space available to the label.

Then the Icon can be used an on component that takes an Icon without custom painting.

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