[英]Resize image so that it fits JPanel grid
我有一個JPanel具有(5,7),5行,7列的網格布局。
當我嘗試將圖像添加到網格面板時
Img = new ImageIcon("ImagePath");
JLabel Label = new JLabel(Img);
add(picLabel);
對於我的網格面板來說,圖像似乎太大了,而網格面板上只顯示了一小部分圖像。
如何將圖像添加到網格,以便圖像調整為網格大小。
不要使用JLabel和ImageIcon。 相反,我會
paintComponent(Graphics g)
方法 g.drawImage(image,....)
重載,該重載允許重新調整圖像的大小,以使其填充JPanel。 鏈接:
查看此重載:
public abstract boolean drawImage(Image img,
int x,
int y,
int width,
int height,
ImageObserver observer)
或這一個:
public abstract boolean drawImage(Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
ImageObserver observer)
編輯
例如,
// 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);
}
}
}
如何將圖像添加到網格,以便圖像調整為網格大小。
看看Darryl的Stretch Icon 。
它將動態調整自身大小以填充標簽可用的空間。
然后,可以將Icon用作啟用Icon的on組件,而無需自定義繪畫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.