java 将图像添加到 GridLayout 中的单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14558959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding images to cells in a GridLayout
提问by Jesper Tuborg Madsen
Trying to create a gridLayout and fill it with images, where is it going wrong?
尝试创建一个 gridLayout 并用图像填充它,哪里出错了?
ImageIcon grassIcon = new ImageIcon("images/grass_tile.jpg");
JPanel panel = new JPanel(new GridLayout(haps,snaps,0,0));
JLabel labels[] = new JLabel[(haps*snaps)];
for (int i = 0; i < haps*snaps; i++)
{
labels[i] = new JLabel(grassIcon);
panel.add(labels[i]);
}
frame.add(panel);
回答by nsutgio
Just try to check your image path if you have it correctly. Or maybe for a test if you can really make the image appear, try to make it an absolute path. And also, please elaborate your problems in there.
如果正确,请尝试检查您的图像路径。或者也许为了测试您是否真的可以使图像出现,请尝试使其成为绝对路径。另外,请在那里详细说明您的问题。
回答by Jesper Tuborg Madsen
As ben75 writes, it needed frame.pack(); Creds to him!
正如 ben75 所写,它需要 frame.pack(); 给他信用!
回答by Alya'a Gamal
Show the frame by using frame.setVisible(true);
使用frame.setVisible(true)显示框架;
ImageIcon grassIcon = new ImageIcon("images/grass_tile.jpg");
JPanel panel = new JPanel(new GridLayout(haps,snaps,0,0));
JLabel labels[] = new JLabel[(haps*snaps)];
for (int i = 0; i < haps*snaps; i++)
{
labels[i] = new JLabel(grassIcon );
panel.add(labels[i]);
}
frame.add(panel);
frame.pack();
frame.setVisible(true);