我有一个简单的棋盘,我也在尝试添加棋子。我想更改图标图像而不添加更多正方形。我怎样才能做到这一点?
我只想覆盖那个正方形中的图像,但是我现在所拥有的似乎增加了更多正方形。
象棋正方形类采用棋子类型和x / y坐标。
代码如下:
棋盘:
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。不会将ChessSquare添加到面板中。
正如您所说的那样,无论如何您都不想创建一个新的ChessSquare,您只想更改现有正方形的图标。因此,代码应类似于:
ChessSquare piece = squares[4][7];
piece.setIcon( yourKingIcon );
您创建ChessSquare的基本代码是错误的。您应该将Icon作为参数传递。您不应该阅读ChessSquare类中的图标。