Java 我想在我的jpanel单元格中显示一张图片,但我的代码不起作用
公共静态JPanel[][]creationGrille(JPanel内容)引发IOException{Java 我想在我的jpanel单元格中显示一张图片,但我的代码不起作用,java,swing,Java,Swing,公共静态JPanel[][]creationGrille(JPanel内容)引发IOException{ ImageIcon monImage = new ImageIcon("src\\images\\tree.png"); JLabel imageLab = new JLabel(); imageLab.setIcon(monImage); //JPanel affichage Grille JPanel contentGrille = new JP
ImageIcon monImage = new ImageIcon("src\\images\\tree.png");
JLabel imageLab = new JLabel();
imageLab.setIcon(monImage);
//JPanel affichage Grille
JPanel contentGrille = new JPanel();
//On définit le layout à utiliser pour la grille
contentGrille.setLayout(new GridLayout(14, 14));//14 lignes, 14 colonnes
content.add(contentGrille,BorderLayout.CENTER);
JPanel cell[][]= new JPanel[14][14];
for(int i=0; i<cell.length; i++){
for(int j=0; j<cell.length; j++){
cell[i][j]= new JPanel();
cell[i][j].setSize(new Dimension(50, 50));
if (i == 5 || i ==6 || i==7 || i==8 || j==5 || j==6 || j==7 || j==8) {
cell[i][j].setBackground(Color.gray);
if((i<5 && j==6) || (i>8 && j==6)){
cell[i][j].setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.white)); // top, left,bottom,right, color
}else if((i==6 && j<5) || (i==6 && j>8)){
cell[i][j].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.white));
}
}else{
cell[i][j].add(imageLab);
//cell[i][j].setBackground(Color.white);
}
contentGrille.add(cell[i][j]);
}
}
return cell;
}
ImageIcon monImage=newimageIcon(“src\\images\\tree.png”);
JLabel imageLab=新的JLabel();
设置图标(monImage);
//JPanel affichage格栅
JPanel contentgrill=新的JPanel();
//关于définit le layour pour la grill的布局
contentgrill.setLayout(新的GridLayout(14,14));//14个直线,14个柱状图
添加(contentgrill,BorderLayout.CENTER);
JPanel单元[][]=新JPanel[14][14];
对于(int i=0;i组件只能属于单个父级/容器,因此您需要为要将图像添加到的每个面板创建一个新的JLabel
“我的代码不工作”预期行为与实际行为?错误消息?请努力澄清您的问题,使我们更容易回答…没有错误消息…我的面板ContentGrill是14*14单元格,我想在一些单元格中显示picture tree.png,而不是在所有的contentGrilleA组件只能属于一个父/包含呃,因此您需要为每个要添加图像的面板创建一个新的JLabel 1)为了更快地获得更好的帮助,发布一个or。2)获取图像的一种方法是热链接到中看到的图像。我声明:JLabel imageLab[][]=new JLabel[14][14];在我将此添加到我的else条件后:imageLab[i][j]=new JLabel();imageLab i][j].setIcon(monImage);单元格[i][j]。添加(imageLab[i][j]);但不工作!!cell[i][j]。添加(新JLabel(monImage));