我使用 JPanel 为黑白棋创建了一个基本的 GUI,以在 GridLayout 中表示棋盘。在播放乐曲的那一刻,点击的方块会改变颜色。我一直试图让一个圆形的部分来改变和背景保持不变。
我已经搜索了很多,我似乎无法找到一种方法来做到这一点?
- 编辑 -
构造函数的代码。播放乐曲时,鼠标侦听器只会更新棋盘
Public boardGUI(int num){
game = new reversiGame(num, false);
Dimension boardSize = new Dimension(600, 600);
numSquares = num;
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
board = new JPanel();
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
board.setLayout( new GridLayout(numSquares, numSquares) );
board.setPreferredSize( boardSize );
board.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < (numSquares * numSquares); i++) {
JPanel square = new JPanel( new BorderLayout() );
square.setBorder(BorderFactory.createLineBorder(Color.black));
square.setBackground(Color.green);
board.add( square );
int row = (i/numSquares);
int col = (i % numSquares);
if ((row + 1 == numSquares / 2 & col + 1 == numSquares/2) || row == numSquares/2 & col == numSquares/2){
square.setBackground(Color.white);
}
if ((row + 1 == numSquares / 2 & col == numSquares/2) || row == numSquares/2 & col + 1 == numSquares/2){
square.setBackground(Color.black);
}
}
}
updateBaord 函数
public void updateBoard(){
int x = 0;
int y = 0;
ImageIcon black = new ImageIcon("Images/large-black-sphere.ico");
ImageIcon white = new ImageIcon("Images/large-white-sphere.ico");
for(int i = 0; i < numSquares; i++){
for(int j = 0; j < numSquares; j++){
x = i * (600/numSquares);
y = j * (600/numSquares);
Component c = board.findComponentAt(x, y);
GridType g = game.getGridType(i, j);
if (g.equals(GridType.WHITE)){
JPanel temp = (JPanel) board.getComponent( i + j );
piece = new JLabel(white);
temp.add(piece);
//c.setBackground(Color.white);
}
else if(g.equals(GridType.BLACK)){
JPanel temp = (JPanel)board.getComponent( i + j );
piece = new JLabel(black);
temp.add(piece);
//c.setBackground(Color.black);
}
else{
//c.setBackground(Color.GREEN);
}
}
}
}