Results 1 to 7 of 7
  1. #1
    Burnett98 is offline Member
    Join Date
    Jun 2012
    Posts
    13
    Rep Power
    0

    Default Help with a jFrame freezing

    Hello, I am currently trying to program some sort of "RPG" and I have come across a problem. I am currently using an object for a battle, and I just pass it your character and an enemy and it will automatically initiate a battle and set everything up. I am currently running into a problem. Halfway during this process, it will suddenly freeze and become unresponsive. I think it has something to do with the method that i have for only letting the enemy attack again once you have pressed the button to choose your spell. I am using a for loop where the variable is set at 0, and the deciding factor 1. When you press the button, it triggers a boolean to change states, hopefully stop the for loop. It will then let the enemy attack, and then it will switch the boolean back. For some reason, as soon as the jFrame is initiated, all the options and such will set, and then it will suddenly freeze. It will not respond to anything, and I have to go into my IDE(Netbeans) and force it to stop. Does anyone know what is going on. I have tried to go into the IDE and see which line it is stuck on, but it is not displaying it, like it normally does. The entire IDE seems to slow down incredibly until I terminate the program from running. Here is the code for the entire class.



    Java Code:
    package mainFiles;
    
    
    import java.awt.Color;
    import java.util.Random;
    import javax.swing.JOptionPane;
    /**
     *
     * @author SamBurnett
     */
    public class Battle extends javax.swing.JFrame {
    
        /**
         * Creates new form Battle
         */
        public Battle() {
            initComponents();
        }
    
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jLabel1 = new javax.swing.JLabel();
            jButton3 = new javax.swing.JButton();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton4 = new javax.swing.JButton();
            jProgressBar1 = new javax.swing.JProgressBar();
            jProgressBar2 = new javax.swing.JProgressBar();
            jProgressBar3 = new javax.swing.JProgressBar();
            jLabel2 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jButton5 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowOpened(java.awt.event.WindowEvent evt) {
                    formWindowOpened(evt);
                }
            });
    
            jLabel1.setText("Enemy");
    
            jButton3.setText("jButton3");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });
    
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jButton2.setText("jButton2");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            jButton4.setText("jButton4");
            jButton4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton4ActionPerformed(evt);
                }
            });
    
            jProgressBar1.setBackground(new java.awt.Color(255, 255, 255));
            jProgressBar1.setForeground(new java.awt.Color(0, 255, 0));
    
            jProgressBar3.setBackground(new java.awt.Color(255, 255, 255));
            jProgressBar3.setForeground(new java.awt.Color(0, 255, 0));
    
            jLabel2.setText("Hero");
    
            jTextField1.setEditable(false);
            jTextField1.setFocusable(false);
            jTextField1.setRequestFocusEnabled(false);
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jButton5.setText("Start");
            jButton5.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton5ActionPerformed(evt);
                }
            });
    
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .add(0, 113, 113)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, jProgressBar2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, jProgressBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jTextField1)
                            .add(69, 69, 69)
                            .add(jLabel2))))
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jProgressBar3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(layout.createSequentialGroup()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jButton1)
                                .add(jButton3))
                            .add(61, 61, 61)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(jButton2)
                                .add(layout.createSequentialGroup()
                                    .add(jButton5)
                                    .add(58, 58, 58)
                                    .add(jButton4)))))
                    .add(0, 0, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jProgressBar3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(18, 18, 18)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 49, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 17, Short.MAX_VALUE)
                    .add(jLabel2)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jProgressBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jProgressBar2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(18, 18, 18)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton1)
                        .add(jButton2))
                    .add(18, 18, 18)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton3)
                        .add(jButton4)
                        .add(jButton5))
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>
    
        private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
            setup(Main.hero, Main.tempEnemy);
            JOptionPane.showMessageDialog(null, "You are now battling " + Main.tempEnemy.name +"!");
            battle();
        }                                 
    
        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
            
        }
    
        private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
           
        }
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            Main.tempDamage = 10;
            Main.tempResourceUp = 0;
            Main.readyForAttack = false;
        }
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            Main.tempDamage = 70;
            Main.tempResourceUp = -50;
            Main.readyForAttack = false;
        }
    
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            Main.tempDamage = -30;
            Main.tempResourceUp = -20;
            Main.readyForAttack = false;
        }
    
        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            Main.tempHolder = Main.hero.health;
            Main.hero.health = Main.hero.mana;
            Main.hero.mana = Main.tempHolder;
            Main.readyForAttack = false;
        }
    
        /**
         * @param args the command line arguments
         */
        
        public static int attack()
        {
            double damage = Main.tempDamage;
            int resourceGain = Main.tempResourceUp;
            if(Main.hero.typeIsWarrior)
            {
                double modifier = Main.hero.strength * 0.1;
                damage = damage * modifier;
                Main.hero.rage = Main.hero.rage + resourceGain;
            }
            if(Main.hero.typeIsWizard)
            {
                double modifier = Main.hero.intelligence * 0.05;
                damage = damage * modifier;
                Main.hero.mana = Main.hero.mana + resourceGain;
            }
            if(Main.hero.typeIsRogue)
            {
                double modifier = Main.hero.dexterity * 0.1;
                Main.hero.focus = Main.hero.focus + resourceGain;
            }
            
            return (int)damage;
        }
        public void battle()
        {
        
            Random rand = new Random();
            for(int i = 0; i < 1;)
    		{
    			
                            refresh();
                            Main.hero.resourcesRefresh();
                            for(int j = 0; j < 1;)
                            {
                                if(Main.readyForAttack = false)j = 1;
                            }
    			int attackNum = rand.nextInt(Main.tempEnemy.numberOfAttacks);
    			int heroDamageDoneOrHealthHealed;
    			if(attackNum == 0)
    			{
    				jTextField1.setText("They used " + Main.tempEnemy.attackOneName + "!");
    				Main.hero.health = Main.hero.health - Main.tempEnemy.attackOneDamage/Main.hero.resistance;
                                    refresh();
    			}
    			else if(attackNum == 1)
    			{
    				jTextField1.setText("They used " + Main.tempEnemy.attackTwoName + "!");
    				Main.hero.health = Main.hero.health - Main.tempEnemy.attackTwoDamage/Main.hero.resistance;
                                    refresh();
    			}
    			else if(attackNum == 2)
    			{
    				jTextField1.setText("They used " + Main.tempEnemy.attackThreeName + "!");
                                    Main.hero.health = Main.hero.health - Main.tempEnemy.attackThreeDamage/Main.hero.resistance;
                                    refresh();
    			}
                            else if(attackNum == 3)
                            {
    				jTextField1.setText("They used " + Main.tempEnemy.attackFourName + "!");
                                    Main.hero.health = Main.hero.health - Main.tempEnemy.attackFourDamage/Main.hero.resistance;
                                    refresh();
    			}
    			
    			heroDamageDoneOrHealthHealed = attack();
    			if(heroDamageDoneOrHealthHealed < 0)
    			{
    				Main.hero.health = Main.hero.health - heroDamageDoneOrHealthHealed;
    			}
    			else
    			{
    				Main.tempEnemy.health = Main.tempEnemy.health - heroDamageDoneOrHealthHealed;
    			}
                            boolean victory;
                            if(Main.tempEnemy.health <= 0)
    			{
    				i = 1;
    				victory = true;
    				JOptionPane.showMessageDialog(null, "You have just gained " + Main.tempEnemy.experienceGiven + " points of experience");
    				Main.hero.experience = Main.hero.experience + Main.tempEnemy.experienceGiven;
    				if (Main.hero.experience >= 100)
    				{
    					Main.hero.levelUp();
    				}
    			}
    			else if(Main.hero.health <= 0)
    			{
    				i = 1;
    				victory = false;
    			}
                            Main.readyForAttack = true;
    		}
        }
    
        public void setup(Hero x, Enemy y)
        {
            jProgressBar3.setMaximum(y.health);
            jProgressBar3.setValue(y.health);
            jProgressBar1.setMaximum(x.maxHealth);
            jProgressBar1.setValue(x.health);
            if (x.typeIsWizard)
                    {
                        jButton1.setText("Arcane Missles");
                        jButton2.setText("Fireball");
                        jButton3.setText("Heal");
                        jButton4.setText("Convert");
                        jProgressBar2.setForeground(Color.blue);
                        jProgressBar2.setMaximum(x.maxMana);
                        jProgressBar2.setValue(x.mana);
                    }
            else if(x.typeIsWarrior)
                    {
                        jButton1.setText("Slash");
                        jButton2.setText("Stab");
                        jButton3.setText("Massive Blow");
                        jButton4.setText("Absorb");
                        jProgressBar2.setForeground(Color.red);
                        jProgressBar2.setMaximum(x.maxRage);
                        jProgressBar2.setValue(x.rage);
                    }
            else if(x.typeIsRogue)
                    {
                        jButton1.setText("Gash");
                        jButton2.setText("Focus");
                        jButton3.setText("Poison Arrow");
                        jButton4.setText("Back Stab");
                        jProgressBar2.setForeground(Color.yellow);
                        jProgressBar2.setMaximum(x.maxFocus);
                        jProgressBar2.setValue(x.focus);
                    }
        }
        public void refresh()
        {
            jProgressBar1.setValue(Main.hero.health);
            jProgressBar3.setValue(Main.tempEnemy.health);
            if(Main.hero.typeIsWarrior)jProgressBar2.setValue(Main.hero.rage);
            if(Main.hero.typeIsRogue)jProgressBar2.setValue(Main.hero.focus);
            if(Main.hero.typeIsWizard)jProgressBar2.setValue(Main.hero.mana);
        }
                
                
        public static void main(Enemy x) {
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with the
             * default look and feel. For details see
             * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Battle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Battle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Battle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Battle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
            Main.tempEnemy = x;
            
            
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new Battle().setVisible(true);
                    
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JButton jButton4;
        private javax.swing.JButton jButton5;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JProgressBar jProgressBar1;
        private javax.swing.JProgressBar jProgressBar2;
        private javax.swing.JProgressBar jProgressBar3;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
    }

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help with a jFrame freezing

    Java Code:
    for(int j = 0; j < 1;)
    {
        if(Main.readyForAttack = false)j = 1;
    }
    This loop in battle() looks dangerous. You could use System.out.println() to check that you are caught in an infinite loop here.

    -----

    I haven't read read the code closely but loops like this (even once corrected) don't seem right in a GUI program where you want the program to be responsive at all times.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,404
    Rep Power
    20

    Default Re: Help with a jFrame freezing

    Quote Originally Posted by pbrockway2 View Post
    Java Code:
    for(int j = 0; j < 1;)
    {
        if(Main.readyForAttack = false)j = 1;
    }
    This loop in battle() looks dangerous.
    Not only that, the if condition is an assignment, not a comparison.
    Java Code:
    //if(Main.readyForAttack = false)
    if(!Main.readyForAttack)
    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    Burnett98 is offline Member
    Join Date
    Jun 2012
    Posts
    13
    Rep Power
    0

    Default Re: Help with a jFrame freezing

    Oh wow. Thanks for catching that. Well, I went back, fixed all the errors that you guys pointed out, and for the loop, I made it print out either "It went" for if it ended the loop and kept going(Which it shouldn't do), or if it stayed in the loop. It is definitely staying in the loop, but the lag is ridiculous. I can't even resize the window without it taking a minute and a half. Do you guys have any idea if there is a deferent way to do this? I just want this whole loop of him attacking/then you attack to pause indefinitely until you choose your attack. Should I set up some system so that instead of doing it this way, it is set up so that you attack first, and each of the buttons is instead set up to do damage, etc. but then tell the enemy to attack you? I just see a lot of bugs in doing it this way. What are your thoughts on this, because you would know how java would respond to these different ideas better than I would.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,404
    Rep Power
    20

    Default Re: Help with a jFrame freezing

    I for one am not going to try to analyze all that absurdly meandering IDE-generated code. To get better help sooner, post a SSCCE (Short, Self Contained, Correct (Compilable), Example) that demonstrates the problem.

    Since logic rather than layout is the problem, get rid of the GroupLayout. It just adds clutter.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    Burnett98 is offline Member
    Join Date
    Jun 2012
    Posts
    13
    Rep Power
    0

    Default Re: Help with a jFrame freezing

    Actually, I seem to have fixed it. I just ditched loops all together as they were causing more problems than they were fixing. I am just going to use a system that is all activated when you choose your attack, so it cannot start without it and I don't need to system to keep it from doing so. Thanks for your help. I actually noticed a couple more bugs in my program just when I went back and fixed the things you thought were potential issues. Thanks for taking the time to help me fix this.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help with a jFrame freezing

    I am just going to use a system that is all activated when you choose your attack, so it cannot start without it and I don't need to system to keep it from doing so.
    If I understand you correctly that's a better approach. The loop is infinite because (as db pointed out, it's an assignment whose value is false so j never gets incremented) but - worse - the computer ill spend nearly all its time going round and round the loop and never get a chance to react to anything else.

    In a simple GUI program every significant event gets "triggered" in some way: either within the program (button click, key typed, mouse moved, ...) or from the outside (repaint, ...). These events are handled on a single thread (ie one at a time) with nobody sitting around "waiting" as in your code as that would tie up the thread. It's worth going through some Swing tutorials to get a feel for the overall architecture before applying it to your specific task.

Similar Threads

  1. Client Freezing
    By thegreatbenjamino in forum Networking
    Replies: 3
    Last Post: 05-28-2011, 09:03 PM
  2. Terminal freezing (Mac OS)
    By China Diapers in forum New To Java
    Replies: 0
    Last Post: 03-25-2011, 12:10 PM
  3. Movement/KeyListener freezing..
    By AndroidAppNewbie in forum New To Java
    Replies: 4
    Last Post: 03-10-2011, 04:31 PM
  4. Program Freezing While Reading Input
    By airowe in forum New To Java
    Replies: 15
    Last Post: 01-11-2011, 03:38 AM
  5. why does this code keep freezing?
    By berkeley in forum New To Java
    Replies: 4
    Last Post: 06-03-2010, 04:41 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •