在Java网格中更改ImageIcon
我有一个简单的棋盘,我也在尝试添加棋子。我想在不添加更多方块的情况下更改图标图像。我该怎么做 我只想覆盖那个方块中的图像,但是我现在看到的似乎是添加了更多的方块 chess square类采用棋子类型和x/y坐标 代码如下: 棋盘:在Java网格中更改ImageIcon,java,swing,jbutton,chess,imageicon,Java,Swing,Jbutton,Chess,Imageicon,我有一个简单的棋盘,我也在尝试添加棋子。我想在不添加更多方块的情况下更改图标图像。我该怎么做 我只想覆盖那个方块中的图像,但是我现在看到的似乎是添加了更多的方块 chess square类采用棋子类型和x/y坐标 代码如下: 棋盘: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ChessBoard2 { public static void main(String[]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChessBoard2
{
public static void main(String[] Args)
{
JFrame a = new JFrame("Chess");
JPanel panel = new JPanel();
ChessSquare[][] squares = new ChessSquare[8][8];
panel.setLayout(new GridLayout(8,8));
int x = 0;
int y = 0;
for ( x=0; x<8; x++)
for( y=0; y<8; y++)
{
squares[x][y] = new ChessSquare("emptysquare", x, y);
panel.add(squares[x][y]);
}
x=5;y=8;
squares[x][y] = new ChessSquare("king", x, y);
a.setSize(375,375);
a.setContentPane(panel);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChessSquare extends JButton
{
private int xPosition;
private int yPosition;
private String filename;
public ChessSquare(String type, int x, int y)
{
super();
xPosition = x;
yPosition = y;
if (type == "emptysquare")
{ filename = "EmptySquare.jpg";}
if (type == "king")
{ filename = "king.jpg";}
ImageIcon square = new ImageIcon(filename);
setIcon(square);
}
}
谢谢
x=5;y=8;
你不能这样做,因为你会得到一个例外。阵列为8x8,但偏移量为0,因此可以使用值0-7对阵列进行索引
squares[x][y] = new ChessSquare("king", x, y);
该语句所做的只是向数组中添加一个棋盘格。它不会将棋盘格添加到面板中
正如您所说,您无论如何都不想创建新的棋盘格,您只想更改现有棋盘格的图标。所以代码应该是这样的:
ChessSquare piece = squares[4][7];
piece.setIcon( yourKingIcon );
您创建棋盘格的基本代码是错误的。您应该将图标作为参数传递。您不应该在ChessSquare类中读取图标