类中的JButton监听器调用方法给出了NullPointerException

时间:2014-12-11 23:17:33

标签: java swing nullpointerexception jbutton

这里是java的新手,我正在尝试使用GUI进行我的第一个项目。我有一个GameConsole类,包含gamePlay()和userTurn()。我有一个ButtonListener类,它使用调用userTurn()的actionListener构造按钮。但是,每次按下按钮,我都会得到一个NullPointerException。为什么会发生这种情况,我该怎么做才能解决它?

相关代码:

public static final void main (String[] args){
    GameConsole game = new GameConsole();
    game.gamePlay();
}

public class GameConsole {
    public Player user;
    public Player dealer;
    public Deck playingDeck;
    ValidateInput validate = new ValidateInput();

public void gamePlay(){
    //get info from user
    user.addToHand(playingDeck.getTopCard());
    dealer.addToHand(playingDeck.getTopCard());
    user.addToHand(playingDeck.getTopCard());
    dealer.addToHand(playingDeck.getTopCard());

    userTurn();
}

public void userTurn(){
    boolean turn = true;
    do{   //the code breaks at this point. On the first round of gameplay I get the exception pasted
          //below. The second round (after the button is pressed) I get an 
          //Exception in thread "AWT-EventQueue-0      bringing me back here
        JOptionPane.showMessageDialog(null, "The cards you were dealt are: \n" + user.printHand());

        if(user.sumOfHand() == 21){  //no need to continue if user has 21
            System.out.println("You win this round.");
            break;
        } else if (user.sumOfHand() > 21){
            System.out.println("You have busted. You lose this round.");
            break;
        }


        String HSInput = null;
        for(int x = 0; x < 1;){
        HSInput = JOptionPane.showInputDialog("\nThe dealer is showing a " + dealer.getTopCard()
                + "\nYou are currently at " + user.sumOfHand()
                + "\n\nWhat would you like to do?\nHit (H) or Stay (S)?");
        if(validate.containDesiredString(HSInput, "HhSs")) //only accept h and s either caps
            x++;
        }


        if(HSInput.equalsIgnoreCase("H")){  //if the user wants to stay
            user.addToHand(playingDeck.getTopCard()); //deal new card then repeat loop
        } 
        else {
            turn = false;
            }
    } while (turn == true);
}

ButtonListener类......

public class ButtonListener implements ActionListener {

    JButton newRoundButton;

    public ButtonListener(JPanel endGamePanel){

        newRoundButton = new JButton("Start another round");
        newRoundButton.setPreferredSize(new Dimension(150, 50));
        endGamePanel.add(newRoundButton);
        newRoundButton.addActionListener(this);

    }


    @Override
    public void actionPerformed(ActionEvent e) {        
        if(e.getSource() == newRoundButton){
            System.out.println("Hi there for a new round");
                     //I know that this method is entered into because this line will print
            GameConsole game = new GameConsole();
            game.userTurn();
        }
    }

我绝望地迷失了,过去两天一直在圈子里。现在,该程序甚至无法进入userTurn()。我不知道我做了什么,因为几个小时前这不是一个问题。无论哪种方式,我的最终问题是我无法让ButtonListener调用userTurn()类。为什么我现在为userTurn()获得NullPointerException,我该怎么做才能让ActionListener调用userTurn()而不给出NullPointerException

-Hopelessly Lost ...感谢任何帮助!

编辑:堆栈跟踪 线程&#34; main&#34;中的例外情况JAV

a.lang.NullPointerException
    at blackjackControls.GameConsole.userTurn(GameConsole.java:180)
    at blackjackControls.GameConsole.gamePlay(GameConsole.java:119)
    at blackjackControls.Main.main(Main.java:7)

因为它不再进入userTurn(),我无法为此发布跟踪。它确实说它是AWT中的一个主题

ButtonListener类已与现有的ResultPane类结合使用。完整代码是:

public class ResultPanel extends JFrame {

    JFrame frame = new JFrame("Blackjack Game");
    JPanel endGamePanel = new JPanel();
    ImageIcon image;
    JLabel lbl;
    JButton newRoundButton;
    JButton endButton;

    public ResultPanel(){

        frame.setSize(800, 600);
        frame.getContentPane().add(endGamePanel);   //add the panel to the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

        JButton newRoundButton= new JButton("Start another round");
        newRoundButton.setPreferredSize(new Dimension(150, 50));
//      newRoundButton.addActionListener();
        newRoundButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {

                System.out.println("Hi there for a new round");
                GameConsole game = new GameConsole();
                game.userTurn();
            }
        });


        frame.setVisible(true);
    }

    public void winGame(){
        image = new ImageIcon(getClass().getResource("win.jpg"));
        lbl = new JLabel (image);
        endGamePanel.add(lbl);

        frame.setVisible(true);
    }

3 个答案:

答案 0 :(得分:1)

据我所知,你在main中创建了一个新的GameConsole对象,所以我认为这是整个游戏的对象。如果是这种情况,为什么您的按钮会创建一个新的GameConsole对象?我假设您收到NullPointerException,因为您的按钮在尚未拥有User对象的新userTurn()对象上调用GameConsole方法,因此user.sumOfHand()例如userTurn会抛出异常。

您的按钮应调用您在主要内容中创建的GameConsole对象上的JButton newRoundButton= new JButton("Start another round"); newRoundButton.setPreferedSize(new Dimension(150, 50)); newRoundButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Hi there for a new round"); game.userTurn(); } }); endGamePanel.add(newRoundButton); 方法,而不是新方法。

代码建议:

GameConsole

这假设您的小组构建的任何类都知道您的GameConsole对象。如果此类是game.对象本身,则只需删除GameConsole如果在GameConsole对象中创建了该类的对象,只需将GameConsole game对象传递给该类即可该类构造函数中的参数GameConsole,如果需要,使其成为该类中的字段。要从该对象传递this对象,请传递{{1}}。

答案 1 :(得分:0)

您需要初始化对象。

 public class GameConsole {
    public Player user = new Player();
    public Player dealer = new Player();
    public Deck playingDeck = new Deck();

你可以这样做

答案 2 :(得分:0)

在查看超过1100行代码后,我的用户为null,因为我在gamePlay()中再次声明它,这使它成为局部变量。 ONE WORD将我困扰了3天。哎呀!