1
我有一個簡單的棋盤,我正在嘗試添加棋子。我想更改圖標圖像而不添加更多方塊。我怎樣才能做到這一點?在Java網格中更改ImageIcon
我只是想覆蓋在那個廣場的圖像,但是我現在似乎增加了更多的方塊。
國際象棋方塊類採取件類型和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);
}
}
感謝。