JFrame踢出我不明白的错误

时间:2019-04-24 07:12:31

标签: java swing nullpointerexception jframe

我正在为大学作业创建一个游戏,并试图在JFrame中按下按钮时在我的GameEnviroment类中设置一个变量,但是它踢出了以下错误。我通过在类的变量声明中声明该类的新实例找到了一种解决方法,但是我需要在多个JFrame之间不断传递相同的实例。下面是JFrame代码和我尝试创建/传递实例的类。

当我尝试设置实例游戏的游戏天数变量时,错误似乎在第52行中。我曾尝试过其他吸气剂和吸气剂,但似乎都不起作用

这是我的JUnit窗口:

package displays;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JSlider;

import main.GameEnviroment;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SelectDays {

    private JFrame frmHowManyDay;
    public GameEnviroment game;
    public int numInt;
    /**
     * Launch the application.
     */
    /**
     * Create the application.
     */
    public SelectDays() {
        GameEnviroment game = new GameEnviroment();
        initialize();

    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmHowManyDay = new JFrame();
        frmHowManyDay.setTitle("How Many Day Would You Like Your Adventure To Last?");
        frmHowManyDay.setBounds(100, 100, 630, 192);
        frmHowManyDay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmHowManyDay.getContentPane().setLayout(null);

        final JComboBox comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}));
        comboBox.setBounds(259, 12, 96, 64);
        frmHowManyDay.getContentPane().add(comboBox);

        JButton btnNewButton = new JButton("OKAY");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                int number = Integer.parseInt((String) comboBox.getSelectedItem());
                game.setGameDays(number);
                System.out.println(game.getGameDays());
                ShipAndCrew shipAndCrew = new ShipAndCrew(game);
                shipAndCrew.getFrmSelectCrew().setVisible(true);
                //move to the next window
            }
        });
        btnNewButton.setBounds(250, 106, 120, 25);
        frmHowManyDay.getContentPane().add(btnNewButton);
    }

    public JFrame getFrmHowManyDay() {
        return frmHowManyDay;
    }

    public void setFrmHowManyDay(JFrame frmHowManyDay) {
        this.frmHowManyDay = frmHowManyDay;
    }

    public GameEnviroment getGame() {
        return game;
    }

    public void setGame(GameEnviroment game) {
        this.game = game;
    }
}

这是我的GameEnviroment类:(删除了一些方法,因为它们不重要)


public class GameEnviroment {
    int gameDays = 0;
    int shipPieces;
    int shipPiecesFound = 0;
    int planetCount;
    int crewMemeberCount = 0;
    boolean allFound = false;
    SpaceShip spaceShip;
    Planet currentPlanet;
    public ArrayList<Planet> planets = new ArrayList<Planet>();

    public GameEnviroment() {
        this.gameDays = 0;
    }

    //AAAAEG
    /*
    public static void main(String args[]) {
        GameEnviroment game = new GameEnviroment();
        //open loading screen, then open
        //select days
        System.out.println("Welcome to the game bby ;)");
        game.init(game);
        System.out.println("Welcome travellers aboard the ship " + game.spaceShip.getName() + " with crew");
        System.out.println(game.spaceShip.getCrewList());
        System.out.println("You will have " + game.gameDays + " days to explore the system with " + game.planetCount + " Planets");
        System.out.println("Here is your map");
        System.out.println(game.planets);
        game.currentPlanet = game.planets.get(ThreadLocalRandom.current().nextInt(0, game.planets.size()));
        game.planets.remove(game.currentPlanet);
        for(int i = 1; i <= game.gameDays; i++) {
            //now we play the game
            System.out.println("It is day " + i + " what would you like to do first?");
            game.allFound = game.gameday(game);
            if(game.allFound) {
                i = game.gameDays;
            }
            //we need random events to happen during the night??? 'game.gameNight()?
        }
    }
    */

    public void init(GameEnviroment game) {
        //this is for selecting charecters and lenght
        shipPieces = Math.round((gameDays*2)/3);
        //here we need to create a new spaceship object
        //need to init planets
        planetCount = gameDays;
        for(int j = 0; j < planetCount; j++) {
            //now we generate the correct amount of planets
            //name, part present,  int foodDropMax, int healthDropMax, int moneyDropMax
            if(j < game.shipPieces) {
                Planet planet = new Planet("name", true, randomPcChance(70), randomPcChance(50), randomPcChance(60));
                planets.add(planet);
            }else {
                Planet planet = new Planet("name", false, randomPcChance(70), randomPcChance(50), randomPcChance(60));
                planets.add(planet);
            }
        }
    }


    public boolean gameday(GameEnviroment game) {
        //returns if all the pieces have been found
        //each gameday this loop is called
        //goes to a random planet when the player wants to and is able to, removes it from the list of planets
        //check if all pieces have been found
        String whatsHappend = checkRandomEvents(game);
        System.out.println(whatsHappend);
        Scanner scanner = new Scanner(System.in);
        String tempCrewName = "c";
        while(tempCrewName.equals("x") != true) {
            System.out.println("What Charecter would you like to use?");
            tempCrewName = scanner.next();
            if(tempCrewName.equals("x") != true) {
                charActions(tempCrewName, game);
            }
            if(game.shipPieces == game.shipPiecesFound) {
                System.out.println("You found all the bits! congrats");
                return true;
            }
        }
        for(CrewMember crewMember: game.spaceShip.crewList) {
            crewMember.setActionsLeft(2);
            //how are we doing the degrading of health and shit
            crewMember.setTiredness(crewMember.getTireddeg() * 30);
            crewMember.setHunger(crewMember.getHungerdeg() * 30);
            //reset all actions left for chars and check health/hunger ect
        }
        return false;
    }

    public int getGameDays() {
        return gameDays;
    }

    public void setGameDays(int gameDays) {
        this.gameDays = gameDays;
    }

    public int getShipPieces() {
        return shipPieces;
    }

    public void setShipPieces(int shipPieces) {
        this.shipPieces = shipPieces;
    }

    public int getShipPiecesFound() {
        return shipPiecesFound;
    }

    public void setShipPiecesFound(int shipPiecesFound) {
        this.shipPiecesFound = shipPiecesFound;
    }

    public int getPlanetCount() {
        return planetCount;
    }

    public void setPlanetCount(int planetCount) {
        this.planetCount = planetCount;
    }

}

我希望它设置gameDays的变量并继续,但是显示此错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at displays.SelectDays$1.actionPerformed(SelectDays.java:52)
    at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
    at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
    at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
    at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
    at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:270)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6589)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
    at java.desktop/java.awt.Component.processEvent(Component.java:6354)
    at java.desktop/java.awt.Container.processEvent(Container.java:2261)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4966)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2319)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4798)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4914)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4543)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4484)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2305)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2772)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4798)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
    at java.desktop/java.awt.EventQueue.access$600(EventQueue.java:97)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

1 个答案:

答案 0 :(得分:1)

您不是在构造函数中初始化类成员,而是声明和初始化新的局部变量

GameEnviroment game = new GameEnviroment();

像这样初始化它

game = new GameEnviroment();