我爲Reversi創建了一個基本的GUI,使用JPanel來表示GridLayout中的板。在播放一段作品時,被點擊的方塊會改變顏色。我一直試圖讓一個圓形的部分,而不是改變和背景保持不變。使用Java Swing爲Reversi GUI創建遊戲片
我周圍搜索了很多,我似乎無法找到一種方法來做到這一點?
- 編輯 -
構造函數的代碼。當一塊被打出一個鼠標監聽剛剛更新板
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);
}
}
}
}
向我們展示您正在使用的代碼或可能能夠幫助我們的東西。這裏沒有足夠的信息。 – Deco
一種方法是簡單地在JPanel或其他JComponent的paintComponent方法中繪製或不繪製橢圓。要點是將遊戲邏輯與遊戲GUI分開,並使用邏輯或模型作爲決定哪些圈子在哪裏繪製的基礎。 –