2014-03-25 24 views
1

我正在製作一個項目的棋盤,我必須使用JButtons。我想剛纔設置的板了一個空白的形象,我爲每個瓦,這是我的代碼有:從JButton製作一個棋盤

驅動

public class Driver 
{ 
    public static void main (String[] args) 
    { 
    new ChessBoard(); 
    } 
} 

ChessSquare

import javax.swing.*; 
import java.awt.*; 

public class ChessSquare 
{ 
    public ImageIcon pieceImage; 
    /** The square's location */ 
    private int xCoord; 
    private int yCoord; 

    /** Constructor for the squares */ 
    public ChessSquare(ImageIcon thePieceImage, int theXCoord, int theYCoord) 
    { 
    pieceImage = thePieceImage; 
    xCoord = theXCoord; 
    yCoord = theYCoord; 
    } 

    public int getXCoord() 
    { 
    return xCoord; 
    } 

    public int getYCoord() 
    { 
    return yCoord; 
    } 
} 

ChessBoard

public class ChessBoard 
{ 
    public ChessBoard() 
    { 
    JFrame board = new JFrame(); 
    board.setTitle("Chess Board!"); 
    board.setSize(500,500); 
    board.setLayout(new GridLayout(8,8)); 

    JPanel grid[][] = new JPanel[8][8]; 

    ImageIcon empty = new ImageIcon("/pieces/EmptySquare.jpg"); 

    for(int x = 0; x<8; x++) 
    { 
    for(int y = 0; y<8; y++) 
    { 
     ChessSquare s = new ChessSquare(empty, x, y); 
     JButton square = new JButton(s.pieceImage); 
     grid[x][y].add(square); 
     board.setContentPane(grid[x][y]); 
    } 
    } 
    board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    board.setVisible(true); 
    } 
} 

我的代碼編譯好,但是當我運行它,我得到這個錯誤:

Exception in thread "main" java.lang.NullPointerException at ChessBoard.(ChessBoard.java:23) at Driver.main(Driver.java:8)

我不知道該做些什麼來解決這個錯誤。感謝您的任何幫助:)

+0

錯誤指向ChessBoard。Java第23行。如果您指出該行,它將幫助更快地找到問題。 –

+0

*「用JButtons製作一個棋盤」*請參閱[製作一個強大的,可調整大小的國際象棋GUI](http://stackoverflow.com/q/21142686/418556)以獲得先機.. –

回答

3

其中一個可能的原因是ImageIcon empty = new ImageIcon("/pieces/EmptySquare.jpg"); ...

圖像的路徑建議您使用嵌入的資源,但ImageIcon(String)將該值看作是文件,但不能使用嵌入資源執行此操作,它們不是文件。

相反,您需要使用更類似ImageIcon empty = new ImageIcon(getClass().getResource("/pieces/EmptySquare.jpg"));的東西。

就我個人而言,我建議您應該使用ImageIO.read(getClass().getResource("/pieces/EmptySquare.jpg")),因爲如果資源無法從某種原因加載,這會導致異常,而不是以靜默方式失敗。

grid[x][y].add(square);也將無法正常工作,因爲你沒有指定什麼grid[x][y]

grid[x][y] = new JPanel(); 
grid[x][y].add(square); 

可能會更好地工作,但我不知道爲什麼你這樣做,做這樣的事情的時候.. 。

JButton grid[][] = new JButton[8][8]; 

//... 

grid[x][y] = square; 

似乎是你想達到什麼樣的更合乎邏輯......

更新...

而不是board.setContentPane(grid[x][y]);你應該使用board.add(grid[x][y]);,其他明智的您將與按鈕替換內容窗格......因爲只能有一個單一的內容窗格中,你只能得到一個按鈕...

+0

非常感謝:)我將JPanels更改爲網格中的JButton,就像您所說的那樣,並且也爲圖像編輯了路徑,但現在它運行時,它只在屏幕上加載一個方塊而不是64。想法爲什麼? 再次感謝。 – user3326045

+0

@ user3326045檢查更新... – MadProgrammer

+0

謝謝,現在很好:)我如何批准(?)你的答案是正確的? – user3326045

3

grid[x][y].add(square);你實際上調用JPanel.add(),因爲數組中的每個元素是一個JPanel。

因此錯誤是因爲grid[x][y]仍然null你會得到一個NullPointerException,如果你在這種情況下,在其上調用的方法,如add()

你要分配的價值,因爲你使用的是陣列

grid[x][y] = square; 
+0

非常感謝:)我像你所說的那樣將JPanels更改爲網格中的JButtons,並且也爲圖像編輯了路徑,但現在它運行時,它只會在屏幕上加載一個方塊而不是64個。任何想法是爲什麼?再次感謝 – user3326045