[英]Resize image so that it fits JPanel grid
I have a JPanel with grid layout of (5 , 7 ) , 5 rows , 7 columns. 我有一个JPanel具有(5,7),5行,7列的网格布局。
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. 不要使用JLabel和ImageIcon。 Instead, I'd 相反,我会
paintComponent(Graphics g)
method 重写其paintComponent(Graphics g)
方法 g.drawImage(image,....)
overload that allows for re-sizing of the image so that it fills the JPanel. 调用g.drawImage(image,....)
重载,该重载允许重新调整图像的大小,以使其填充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 . 看看Darryl的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. 然后,可以将Icon用作启用Icon的on组件,而无需自定义绘画。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.