Java - Игра Tic Tac Toe Swing - Ошибки

Я делаю игру в крестики-нолики на Java, создал графический интерфейс и хотел запустить его, чтобы проверить, но получаю несколько ошибок. Я не уверен, почему, и надеялся, что кто-нибудь объяснит, почему появляются эти ошибки и что я должен сделать, чтобы их исправить. Я получаю следующие ошибки: Исключение в потоке "main" java.lang.NullPointerException в TicTacToeSwing.(TicTacToeSwing.java:84) в TicTacToeSwing.main(TicTacToeSwing.java:180)

Вот мой код: (обратите внимание: я еще не выполнил расчеты, потому что хотел сначала запустить графический интерфейс). Если вы знаете о лучшей практике, которую я должен рассмотреть, во что бы то ни стало, дайте мне знать.

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;

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

//Крестики-нолики

    public class TicTacToeSwing extends JFrame
    implements ActionListener { 

//JButtons

//private JButton button1 = new JButton("");    
private JButton jbtnTicTacToe1;
private JButton jbtnTicTacToe2;
private JButton jbtnTicTacToe3;
private JButton jbtnTicTacToe4;
private JButton jbtnTicTacToe5;
private JButton jbtnTicTacToe6;
private JButton jbtnTicTacToe7;
private JButton jbtnTicTacToe8;
private JButton jbtnTicTacToe9;

private JButton jbtnExit;
private JButton jbtnReset;

//JFrame window = new JFrame("Tic-Tac-Toe Swing ");
private JFrame window = new JFrame("Tic-Tac-Toe");


//labels
private JLabel jlblPlayerX = new JLabel ("X");
private JLabel jlblPlayerO = new JLabel ("O");

//text fields
JTextField jtfName = new JTextField(20);
private JTextField jtfPlayerX = new JTextField("X");
private JTextField jtfPlayerO = new JTextField("O");

//Panels
JPanel jpnlMain = new JPanel ();
    JPanel jpnlFamily = new JPanel();
    JPanel jpnlNorth = new JPanel();
    JPanel jpnlSouth = new JPanel();
    JPanel jpnlCenter = new JPanel();
    JPanel jpnlTop = new JPanel();
    JPanel jpnlBottom = new JPanel();

//Class Constructor
public TicTacToeSwing () {

    //Prepare JFrame/Window
    super ("Tic Tac Toe");
    setSize(400,400);
    setTitle("Tic Tac Toe Swing");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set the layouts for 3 rows and 3 columns
    jpnlMain.setLayout(new BorderLayout(3,3));
    jpnlCenter.setLayout(new GridLayout());
    jpnlSouth.setLayout(new GridLayout());
    jpnlTop.setLayout(new BorderLayout());
    jpnlBottom.setLayout(new BorderLayout());

    //Center Panel
    jpnlCenter.add(jlblPlayerX);
    jpnlCenter.add(jlblPlayerO);

    //identify each JButton
    jbtnReset.setActionCommand("Reset");
    jbtnExit.setActionCommand("Exit");

    //register JButton for event handling by using the THIS keyword - THIS class will handle the events
    jbtnReset.addActionListener(this);
    jbtnExit.addActionListener(this);

    /*Add Buttons To The Window*/
    window.add(jbtnTicTacToe1);
    window.add(jbtnTicTacToe2);
    window.add(jbtnTicTacToe3);
    window.add(jbtnTicTacToe4);
    window.add(jbtnTicTacToe5);
    window.add(jbtnTicTacToe6);
    window.add(jbtnTicTacToe7);
    window.add(jbtnTicTacToe8);
    window.add(jbtnTicTacToe9);

    /*Add The Action Listener To The Buttons
    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
    button4.addActionListener(this);
    button5.addActionListener(this);
    button6.addActionListener(this);
    button7.addActionListener(this);
    button8.addActionListener(this);
    button9.addActionListener(this);
    */

    jbtnTicTacToe1.addActionListener(this);
    jbtnTicTacToe2.addActionListener(this);
    jbtnTicTacToe3.addActionListener(this);
    jbtnTicTacToe4.addActionListener(this);
    jbtnTicTacToe5.addActionListener(this);
    jbtnTicTacToe6.addActionListener(this);
    jbtnTicTacToe7.addActionListener(this);
    jbtnTicTacToe8.addActionListener(this);
    jbtnTicTacToe9.addActionListener(this);

    //South Button Panel
    jpnlSouth.add(jbtnReset);
    jpnlSouth.add(jbtnExit);

    /* Instantiate JButtons, put into a method for efficiency
    jbtn1 = instantiateJButton("1", Color.PINK);
    jbtn2 = instantiateJButton("2", Color.PINK);
    jbtn3 = instantiateJButton("3", Color.PINK);
    jbtn4 = instantiateJButton("4", Color.PINK);
    jbtn5 = instantiateJButton("5", Color.PINK);
    jbtn6 = instantiateJButton("6", Color.PINK);
    jbtn7 = instantiateJButton("7", Color.PINK);
    jbtn8 = instantiateJButton("8", Color.PINK);
    jbtn9 = instantiateJButton("9", Color.PINK);
    */

    //Finalize screen layout and publish to the display
    jpnlMain.add(jpnlCenter, BorderLayout.NORTH);
    jpnlMain.add(jpnlSouth, BorderLayout.CENTER);

    //Prepare the container
    Container ca = getContentPane();
    ca.setBackground (Color.LIGHT_GRAY);
    ca.add(jpnlMain);
    setContentPane (ca);

    setVisible(true);
    //end constructor       
}

//CLASS EVENT HANDLER
public void actionPerformed(java.awt.event.ActionEvent e)
{
    //find out which JButton was pressed by using the Action Command
    String sActionCommand = e.getActionCommand();

    //EXIT JButton
    if (sActionCommand == "Exit")
    {
        System.exit(0);
    }

    //RESET JButton
    else if (sActionCommand == "Reset")
    {
        jtfPlayerX.setText("");
        jtfPlayerO.setText("");
    }
}   //end ACTIONPERFORMED (java.awt.event.ActionEvent e)

/**
 * @param args
 */
public static void main(String[] args) {
    //EXECUTION STARTING POINT

    TicTacToeSwing TicTacToeSwing = new TicTacToeSwing();

    //TicTacToeSwing TicTacToeObject = new TicTacToeSwing();

}//end main(String[] args)

   }//end TicTacToeSwing class

person tooheymomster    schedule 22.04.2013    source источник
comment
в какой строке выбрасывается исключение?   -  person Oliver Watkins    schedule 22.04.2013


Ответы (3)


В трассировке стека есть полезная информация о том, что вызывает NPE (jbtnReset, которое появляется в строке 84). Поэтому вам нужно инициализировать jbtnReset:

JButton jbtnReset = new JButton("Reset");    

На самом деле то же самое относится ко всем кнопкам jbtnTicTacToeX, а также jbtnExit.


Побочные проблемы: используйте String#equals для сравнения String содержимого. Оператор == сравнивает содержимое String.

if (sActionCommand == "Exit") {

должно быть

if (sActionCommand.equals("Exit")) {

Это проверяет команду действия для любого компонента с этим String, поэтому вместо этого вы хотите проверить конкретный исходный объект:

if (e.getSource() == jbtnExit) {
person Reimeus    schedule 22.04.2013
comment
для второго предложения побочного выпуска: s/content/references/ - person Chris Pfohl; 22.04.2013
comment
Я не минусовал это ... Мне было интересно, почему кто-то сделал бы это сам. В любом случае, спасибо за помощь и вклад для всех. Исправил все ошибки, кроме этой: - person tooheymomster; 22.04.2013
comment
Несколько маркеров просто означают, что с этой строкой что-то не так. Re сериализуемый класс не объявляет статический финал, это предупреждающее сообщение. См. этот пост - person Reimeus; 22.04.2013

Если вы посмотрите на трассировку стека, такие места, как TicTacToeSwing.java:84, покажут вам, где возникают ошибки. TicTacToeSwing.java — это файл, а :84 означает строку номер 84.

person Nora Powers    schedule 22.04.2013

Где у вас есть:

private JButton jbtnExit;
private JButton jbtnReset;

Пытаться:

private JButton jbtnExit = new JButton("Exit"); 
private JButton jbtnReset = new JButton("Reset");
person Robert    schedule 22.04.2013
comment
Я не минусовал это ... Мне было интересно, почему кто-то сделал бы это сам. Спасибо за помощь и участие всем. Я устранил все ошибки, кроме этой, в строке 24: открытый класс TicTacToeSwing расширяет JFrame, реализует ActionListener{ Несколько маркеров в этой строке. Сериализуемый класс TicTacToeSwing не объявляет статическое поле final serialVersionUID типа long. Возникновение «TicTacToeSwing». - person tooheymomster; 22.04.2013