Reputation: 7766
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.???
Upvotes: 1
Views: 1122
Reputation: 324088
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.
Upvotes: 2
Reputation: 285415
Don't use a JLabel and ImageIcon. Instead, I'd
paintComponent(Graphics g)
methodg.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);
}
}
}
Upvotes: 3