2016-08-15 24 views
0

UPDATE:NVM IM白癡傳遞一個NULL

嗯,所以我最近了解到面板和我試圖重新設計一個井字遊戲項目,沒有重大的開始菜單。

這是我的夢想:Java的JPanel的設計問題

enter image description here

這是我當前的代碼:

public static void modeGUI() { 

    //MAIN JFRAME GUI 
    JFrame gui = new JFrame("TicTacToe"); 
    gui.setVisible(true); 
    gui.setSize(600, 200); 
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //MAIN PANEL 
    JPanel mainPanel = new JPanel(); 
    mainPanel.setLayout(new GridLayout(3, 1)); 
    gui.add(mainPanel); 

    //QUESTION PANEL 
    JPanel questionPanel = new JPanel(); 
    questionPanel.setLayout(new FlowLayout()); 
    JLabel q1 = new JLabel("Please select your mode"); 
    q1.setFont(new Font("Times New Roman", Font.PLAIN, 20)); 
    questionPanel.add(q1); 
    mainPanel.add(questionPanel); 

    //MODE PANEL 
    JPanel modePanel = new JPanel(); 
    modePanel.setLayout(new GridLayout()); 
    JButton[] modeButtons = new JButton[3]; 
    modeButtons[0].setText("First turn"); 
    modeButtons[1].setText("Second turn"); 
    modeButtons[2].setText("P vs. P"); 
    for (JButton modeButton : modeButtons) { 
     modeButton.setFont(new Font("Times New Roman", Font.PLAIN, 20)); 
     modeButton.addActionListener(new Response()); 
     modePanel.add(modeButton); 
    } 
    mainPanel.add(modePanel); 

    //OPTION PANEL 
    JPanel optionsPanel = new JPanel(); 
    optionsPanel.setLayout(new FlowLayout()); 
    mainPanel.add(optionsPanel); 
} 

然而,當我嘗試運行它,它提供了在30行錯誤,這關聯到這條線:modeButtons[0].setText("First turn");。任何人都可以幫忙看看有什麼不對?



這是順便說一句錯誤:在Ttt.main(Ttt.java:7)異常在線程 「主」 顯示java.lang.NullPointerException 在Ttt.modeGUI(Ttt.java:30)

+0

_但是,當我嘗試運行它時,第30行出現錯誤。哪個錯誤?請發佈完整的堆棧跟蹤,它幫助很多 – BackSlash

+0

@BackSlash對不起,並感謝這裏的建議:在線程「主」的異常java.lang.NullPointerException \t at Ttt.modeGUI(Ttt.java:30) \t at Ttt.main(Ttt.java:7) – Archie

回答

1

按鈕數組爲空。

JButton[] modeButtons = new JButton[3]; 

這行創建一個JButtons數組,但每個元素默認設置爲null(與創建所有數組一樣)。

所以,當你嘗試這個

modeButtons[0].setText("First turn"); 

一個NullPointerException被拋出,因爲modeButtons[0]null。您必須先明確定義每個按鈕,然後才能開始分配其值。