将 Png 文件添加到 JButton
Adding a Png-file to a JButton
mainpanel.setLayout(new GridLayout(25,25,1,1));
JButton buttons[][] = new JButton[25][25];
ImageIcon image = new ImageIcon("wall_down_right_player.png");
for(int i=0; i<25; i++){
for(int j=0; j<25; j++){
JButton button = new JButton(image);
buttons[i][j]= button;
mainpanel.add(buttons[i][j]);
}
}
我想知道为什么这不起作用也许有人可以帮助我 :D
按如下操作:
mainpanel.setLayout(new GridLayout(25,25,1,1));
JButton buttons[][] = new JButton[25][25];
Image image = ImageIO.read(getClass().getResource("wall_down_right_player.png"));
for(int i=0; i<25; i++){
for(int j=0; j<25; j++){
JButton button = new JButton();
button.setIcon(new ImageIcon(image));
buttons[i][j]= button;
mainpanel.add(buttons[i][j]);
}
}
更新:
我建议您创建一个文件夹,比如 resources 并将您的图像放在那里。然后,您更改代码如下:
Image image = ImageIO.read(getClass().getResource("resources/wall_down_right_player.png"));`
mainpanel.setLayout(new GridLayout(25,25,1,1));
JButton buttons[][] = new JButton[25][25];
ImageIcon image = new ImageIcon("wall_down_right_player.png");
for(int i=0; i<25; i++){
for(int j=0; j<25; j++){
JButton button = new JButton(image);
buttons[i][j]= button;
mainpanel.add(buttons[i][j]);
}
}
我想知道为什么这不起作用也许有人可以帮助我 :D
按如下操作:
mainpanel.setLayout(new GridLayout(25,25,1,1));
JButton buttons[][] = new JButton[25][25];
Image image = ImageIO.read(getClass().getResource("wall_down_right_player.png"));
for(int i=0; i<25; i++){
for(int j=0; j<25; j++){
JButton button = new JButton();
button.setIcon(new ImageIcon(image));
buttons[i][j]= button;
mainpanel.add(buttons[i][j]);
}
}
更新:
我建议您创建一个文件夹,比如 resources 并将您的图像放在那里。然后,您更改代码如下:
Image image = ImageIO.read(getClass().getResource("resources/wall_down_right_player.png"));`