Ethan Wright
Ethan Wright

Reputation: 41

My Java Swing application launches the same window constantly

I have looked around and I have no idea why it launches a bunch of windows constantly. I haven't found any other posts like this with my exact problem but if there is let me know. I am also very new to java and after watching a video I decided to try to make some simple game with a bit of my own code so it might be a bit messy if so my apology's.

Code:

import java.awt.event.*;
import java.util.Random;

import javax.swing.*;

public class Game extends JFrame {

    // Game Variables
    Enemies newEnemy = new Enemies();
    String enemy;
    static int enemyHealth;
    static int enemyAttackDamage;
    static String imput = "";

    public static void main(String[] args) {

        new Game();

    }

    public Game() {
        // System Variables
        boolean running = true;
        JTextField textField1;
        JTextArea textArea1;

        // GUI Variables
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(900, 600);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.setTitle("Dungeon Drivers Alpha 0.2.3");

        JPanel thePanel = new JPanel();

        textArea1 = new JTextArea(33, 80);
        textArea1.setText("Window launch was Successful.\n");
        textArea1.setEditable(false);
        textArea1.setLineWrap(true);
        textArea1.setWrapStyleWord(true);
        thePanel.add(textArea1);

        JScrollPane scrollbar1 = new JScrollPane(textArea1,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        thePanel.add(scrollbar1);

        textField1 = new JTextField("", 80);
        textField1.setText("Enter Text...");
        thePanel.add(textField1);

        this.add(thePanel);
        this.setVisible(true);

        // System Objects
        Random rand = new Random();

        // Player Variables
        int health = 100;
        int attackDamage = 50;
        int numHealthPotions = 5;
        int healthPotionHealAmount = 30;
        int healthPotionDropChance = 25; // Percentage

        // GAME
        textArea1.append("\tWelcome to the Dungeon!"); // THIS IS THE LAST
                                                       // MESSAGE SEEN THEN IT
                                                       // CONTINUES TO OPEN
                                                       // WINDOWS
        newEnemy.getEnemy();
        FIGHT: while (running) {

            textArea1.append("\n\t-------------------------------------\n");
            textArea1.append("\t# A " + enemy + " has appeared! #");

            while (enemyHealth > 1) {
                textArea1.append("\n\tHealth: " + health);
                textArea1.append("\t" + enemy + "'s Health: " + enemyHealth);
                textArea1.append("\n\tWhat would you like to do?");
                textArea1.append("\t1. Attack!");
                textArea1.append("\t2. Drink Health Potion!");
                textArea1.append("\t3. Run!\n");

                while (running) {
                    textField1.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            imput = textField1.getText();
                            textField1.setText("");
                        }
                    });
                    if (imput.equals("1")) {
                        int damageDealt = rand.nextInt(attackDamage);
                        int damageTaken = rand.nextInt(enemyAttackDamage);

                        enemyHealth -= damageDealt;
                        health -= damageTaken;

                        if (enemyHealth < 1) {
                            textArea1.setText("");
                        }
                        textArea1.setText("");

                        textArea1.append(
                                "\t> You strike the " + enemy + " for " + damageDealt + " Damage.");
                        textArea1.append("\n\t> You recieve " + damageTaken + " in retaliation!");

                        if (health < 1) {
                            textArea1.append("You have no Health left so you ran away.");
                            break;
                        }
                        break;
                    } else if (imput.equals("2")) {
                        if (numHealthPotions > 0) {
                            health += healthPotionHealAmount;
                            numHealthPotions--;
                            textArea1.append("\t> You Drink a health potion for "
                                    + healthPotionHealAmount + "." + "\n\t> You now have " + health
                                    + " Health." + "\n\t> You have " + numHealthPotions
                                    + " Health Potions left.\n");
                            imput = "";
                        } else {
                            textArea1.append(
                                    "\t> You have no Health Potions left! Kill enemies to get them.");
                            imput = "";
                        }
                    } else if (imput.equals("3")) {
                        textArea1.setText(null);
                        textArea1.append("\tYou run from the " + enemy + "!");
                        imput = "";
                        continue FIGHT;
                    }
                    imput = "";
                }
                imput = "";
            }
        }
    }

}

The other file is named Enemies and here is that code:

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class Enemies {

public void getEnemy() {

    Random rand = new Random();
    String[] list = {"Skeleton", "Zombie"};
    Game game = new Game();

    String enemies = list[rand.nextInt(list.length)];
    if(enemies.equals("Skeleton")) {
        int maxHealth = 30;
        int minHealth = 25;
        Game.enemyHealth = ThreadLocalRandom.current().nextInt(minHealth, maxHealth + 1);
        int maxAttackDamage = 15;
        int minAttackDamage = 10;
        Game.enemyAttackDamage = ThreadLocalRandom.current().nextInt(minAttackDamage, maxAttackDamage + 1);
        game.enemy = enemies;
    }
    else if(enemies.equals("Zombie")) {
        int maxHealth = 40;
        int minHealth = 30;
        Game.enemyHealth = ThreadLocalRandom.current().nextInt(minHealth, maxHealth + 1);
        int maxAttackDamage = 20;
        int minAttackDamage = 15;
        Game.enemyAttackDamage = ThreadLocalRandom.current().nextInt(minAttackDamage, maxAttackDamage + 1);
        game.enemy = enemies;
    }
}
}

The final file is called Items and heres that code:

public class Items {
static int healthPotion;
static int ironShard;
static int sharpWoodenSword;
static int averageWoodenSword;
static int dullWoodenSword;
}

Upvotes: 0

Views: 67

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

That's your problem

In your Enemy class in this method:

getEnemy()

creates a new Game object.

So in doing this new Game object will create a new Enemy object that will create a new Game object that will create a new Enemy object.... forever.

If so, the solution is not to do this, but instead to pass the current Game instance into the Enemy class rather than create a new Game instance.

Change Enemies so that it gets the single valid Game object if it nees it. Change this:

public class Enemies {

    public void getEnemy() {

        Random rand = new Random();
        String[] list = {"Skeleton", "Zombie"};
        Game game = new Game();

to this:

public class Enemies {
    private Game game; // variable to hold Game reference:

    public Enemies(Game game) {
        this.game = game; // set the instance
    }

    public void getEnemy() {

        Random rand = new Random();
        String[] list = {"Skeleton", "Zombie"};
        // Game game = new Game();     // no longer need this

Then when you create Enemies, pass in the this Game instance:

Enemies newEnemy = new Enemies(this);

Also as mentioned in comments, the while loops should be present as they are completely contrary to event-driven coding practices. Your first job should be to get completely rid of them, and instead write your code to react to events.

Upvotes: 3

Related Questions