我有一个简单的棋盘,我也在尝试添加棋子。我想更改图标图像而不添加更多方块。我怎样才能做到这一点?
我只想覆盖该正方形中的图像,但是我目前拥有的似乎添加了更多正方形。
国际象棋方块类采用棋子类型和 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);
}
}
谢谢。