2013-03-16 53 views
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); 

    } 
} 

感謝。

回答

3
x=5;y=8; 

你不能這樣做,因爲你會得到一個異常。你的數組是8x8,但它是0偏移量,所以你使用值0-7索引數組。

squares[x][y] = new ChessSquare("king", x, y); 

該聲明所要做的就是將ChessSquare添加到您的數組中。它不會將ChessSquare添加到面板。

正如你所說,你不想創建一個新的ChessSquare,你只是想改變一個現有的廣場的圖標。所以代碼應該是這樣的:

ChessSquare piece = squares[4][7]; 
piece.setIcon(yourKingIcon); 

您創建ChessSquare的基本代碼是錯誤的。您應該將圖標作爲參數傳遞。您不應該閱讀ChessSquare課程中的圖標。