JFrame выкидывает ошибки, я не понимаю - PullRequest
0 голосов
/ 24 апреля 2019

Я создаю игру для университетского задания, и я пытаюсь установить переменную в своем классе GameEnviroment, когда кнопка нажата в JFrame, но она выдает следующие ошибки.Я нашел обходной путь, объявив новый экземпляр класса в переменной переменной класса, но мне нужно продолжать передавать один и тот же экземпляр между несколькими JFrames.Ниже приведен код 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 Ответ

1 голос
/ 24 апреля 2019

Вы не инициализируете своего члена класса здесь в конструкторе, но объявляете и инициализируете новую локальную переменную

GameEnviroment game = new GameEnviroment();

Просто инициализируйте его следующим образом

game = new GameEnviroment();
...