這裏移除的JLabel是我的代碼:添加/從JPanel的
public class GUI
{
JFrame frame;
JPanel squares[][];
public void movePiece(int oriX, int oriY, int destX, int destY)
{
squares[destY][destX] = squares[oriY][oriX];
squares[oriY][oriX] = null;
frame.setVisible(true);
}
/* Constructor credited to stackoverflow user ranzy
http://stackoverflow.com/questions/2535417/chess-board-in-java */
public GUI()
{
frame = new JFrame("Chess");
squares = new JPanel[8][8];
frame.setSize(500, 500);
frame.setLayout(new GridLayout(8, 8));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
squares[i][j] = new JPanel();
if ((i + j) % 2 == 0) {
squares[i][j].setBackground(Color.white);
} else {
squares[i][j].setBackground(Color.orange);
}
frame.add(squares[i][j]);
}
}
ImageIcon pawnW = new ImageIcon(getClass().getResource("pawnW.png"));
ImageIcon knightW = new ImageIcon(getClass().getResource("knightW.png"));
ImageIcon bishopW = new ImageIcon(getClass().getResource("bishopW.png"));
ImageIcon rookW = new ImageIcon(getClass().getResource("rookW.png"));
ImageIcon queenW = new ImageIcon(getClass().getResource("queenW.png"));
ImageIcon kingW = new ImageIcon(getClass().getResource("kingW.png"));
ImageIcon pawnB = new ImageIcon(getClass().getResource("pawnB.png"));
ImageIcon knightB = new ImageIcon(getClass().getResource("knightB.png"));
ImageIcon bishopB = new ImageIcon(getClass().getResource("bishopB.png"));
ImageIcon rookB = new ImageIcon(getClass().getResource("rookB.png"));
ImageIcon queenB = new ImageIcon(getClass().getResource("queenB.png"));
ImageIcon kingB = new ImageIcon(getClass().getResource("kingB.png"));
squares[0][0].add(new JLabel(rookB));
squares[0][1].add(new JLabel(knightB));
squares[0][2].add(new JLabel(bishopB));
squares[0][3].add(new JLabel(queenB));
squares[0][4].add(new JLabel(kingB));
squares[0][5].add(new JLabel(bishopB));
squares[0][6].add(new JLabel(knightB));
squares[0][7].add(new JLabel(rookB));
squares[7][0].add(new JLabel(rookW));
squares[7][1].add(new JLabel(knightW));
squares[7][2].add(new JLabel(bishopW));
squares[7][3].add(new JLabel(queenW));
squares[7][4].add(new JLabel(kingW));
squares[7][5].add(new JLabel(bishopW));
squares[7][6].add(new JLabel(knightW));
squares[7][7].add(new JLabel(rookW));
for (int i = 0; i < 8; i++)
{
squares[1][i].add(new JLabel(pawnB));
squares[6][i].add(new JLabel(pawnW));
}
frame.setVisible(true);
}
}
當用戶移動一塊,我想方塊進行更新。即目標廣場現在應該保持原點廣場jlabel。我試圖用我的movePiece
方法做到這一點。但是,這不是創造我正在尋找的變化。我需要使用添加/刪除方法嗎?另外 - 任何時候我更新電路板時是否需要致電frame.setVisible(true)
?
我沒有看到上面的任何代碼與您的目標有什麼關係。代碼在哪裏試圖移動碎片?你當然知道你的程序只會做你告訴它做的事,不要多也不少。簡單地在板上設置JLabel並不會給程序帶來讓用戶移動標籤的魔力。您最需要一個MouseListener和MouseMotionListener,對吧? movePiece函數中的 –
。 – user2079802
但movePiece本身什麼都不做。什麼叫這個方法?如果從來沒有打過電話,怎麼辦? –