我有一个简单的棋盘,我也想添加棋子。我想在不增加更多方块的情况下改变图标图像。我该怎么做呢?
我只是想覆盖在那个正方形中的图像,但是我现在所拥有的似乎增加了更多的正方形。
象棋方块类接受棋子类型和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 piece = squares[4][7];
piece.setIcon( yourKingIcon );
创建ChessSquare的基本代码是错误的。您应该将Icon作为参数传递。您不应该阅读ChessSquare类中的图标。