Java 如何将图像放入按钮阵列的特定按钮中?
嗨,我对java还是个新手。我需要做一个游戏名Ratsuk witch很像国际象棋,但它只有骑士。所以当骑士不再有移动的空间时,玩家就输了 我为此做了一系列的按钮Java 如何将图像放入按钮阵列的特定按钮中?,java,swing,jbutton,imageicon,Java,Swing,Jbutton,Imageicon,嗨,我对java还是个新手。我需要做一个游戏名Ratsuk witch很像国际象棋,但它只有骑士。所以当骑士不再有移动的空间时,玩家就输了 我为此做了一系列的按钮 import java.awt.*; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public clas
import java.awt.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tablero {
private JButton[][] mesa;
public Tablero() {
mesa = new JButton[8][8];
}
public void cuadriculado(JFrame ventana) {
JPanel panel = new JPanel(new GridLayout(8, 8, 4, 4));
for (int i = 0; i < mesa.length; i++) {
for (int j = 0; j < mesa[0].length; j++) {
mesa[i][j] = new JButton();
mesa[i][j].setPreferredSize(new Dimension(40, 40));
panel.add(mesa[i][j]);
}
}
for (int r = 0; r < mesa.length; r++) {
for (int t = 0; t < mesa[0].length; t++) {
if (r % 2 == 0 || r == 0) {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.BLACK);
} else {
mesa[r][t].setBackground(Color.WHITE);
}
} else {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.WHITE);
} else {
mesa[r][t].setBackground(Color.BLACK);
}
}
}
}
ventana.setContentPane(panel);
ventana.setSize(500, 500);
ventana.setVisible(true);
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0] = new JButton(image);
}
}
import java.awt.*;
导入javax.swing.Icon;
导入javax.swing.ImageIcon;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
公共类表格{
私人JButton[][]mesa;
公共表格({
mesa=新的JButton[8][8];
}
公共无效cuadriculado(JFrame ventana){
JPanel面板=新JPanel(新网格布局(8,8,4,4));
对于(int i=0;i
该文件已编译,但我试图在mesa[0][0]按钮中设置的图像未显示。如何修复此问题?尝试以下方法:
try {
Icon image = ImageIO.read(getClass().getResource("redKnight.gif"));
mesa[0][0] = new JButton();
mesa[0][0].setIcon(new ImageIcon(image ));
} catch (IOException ex) {
}
您不应再次为
mesa[0][0]
创建新的JButton
。但是应该为现有的JButton
对象设置图标
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0].setIcon(image);
`mesa[0][0].setIcon(image);`
您正在创建新的JButton
对象,而不是将图像添加到现有的JButton
对象,因此问题存在
设置mesa[0][0]=new JButton(image)
不会将已添加的JButton
对象添加到要替换的JFrame
。您应该刷新一下Java的基础知识
使用JButton#setIcon(Icon img)
方法将图像添加到已存在的JButton
对象
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0].setIcon(image);
`mesa[0][0].setIcon(image);`
另外,由于在设置帧可见后添加图像,因此可能需要调用JFrame\repaint()
等来刷新帧
或者像这样更改代码:
Icon image = new ImageIcon(getClass().getResource("redKnight.gif"));
mesa[0][0].setIcon(image);
ventana.setContentPane(panel);
ventana.setSize(500, 500);
ventana.setVisible(true);