2011-11-06 55 views
2

我爲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); 
      } 



     } 
    } 

} 
+6

向我們展示您正在使用的代碼或可能能夠幫助我們的東西。這裏沒有足夠的信息。 – Deco

+1

一種方法是簡單地在JPanel或其他JComponent的paintComponent方法中繪製或不繪製橢圓。要點是將遊戲邏輯與遊戲GUI分開,並使用邏輯或模型作爲決定哪些圈子在哪裏繪製的基礎。 –

回答

2

添加的JLabel到遊戲板上的每個網格。然後你可以使用圖標來表示反轉片。然後,當您想要更改換向片時,請更改標籤的圖標。

這裏棋盤例如:How do I make my custom Swing component visible?顯示瞭如何可以這樣做的。

+0

我更改了我的GUI中的updateBoard函數,以添加使用ImageIcon構造的JLabel,但是當我運行它時,它不顯示。有什麼想法嗎? – CNevin561

+0

@ CNevin561,所以你的代碼比我的代碼有什麼不同?我發佈了一個完整的工作示例。我建議你改變圖標不要創建一個新的標籤。 – camickr

2

...使用ImageIcon,但是當我運行它時,它不顯示。

您可能需要調用repaint(); ColorIconMVCGame爲例。

仔細一看,您的updateBoard()方法似乎是在不刪除舊標籤或驗證面板佈局的情況下,將新標籤添加到現有面板。相反,請更新Icon