Results 1 to 9 of 9
Like Tree5Likes
  • 1 Post By Norm
  • 1 Post By JosAH
  • 1 Post By Norm
  • 1 Post By Norm
  • 1 Post By Norm

Thread: The for loop in ActionListener

  1. #1
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Unhappy The for loop in ActionListener

    Hello guys,

    I want to make a game and I have the following:
    A main JFrame which include some text and a Button (The Start Button), and I made an ActionListener for that Button to another ActionListener which have a for, but when I run the project I only see the final of the for loop. How can I solve this problem?

    Thank you.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,456
    Rep Power
    25

    Default Re: The for loop in ActionListener

    What is the loop doing?
    If it is trying to change the GUI, then the last change is the one you'll see.

    Sort of like this:
    x = 2;
    x = 3;
    x = 4;

    Here you see x with a value of 4. The values of 2 and 3 are gone.
    Flopet17 likes this.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,535
    Blog Entries
    7
    Rep Power
    20

    Default Re: The for loop in ActionListener

    You probably run that for loop in the EDT (Event Dispatch Thread); that's the same thread that has to do all the drawing. It can't do that because it has to run you for loop. The remedy is simple: start another thread in your handler and make that other thread run that for loop; the EDT is free to do all the drawing.

    kind regards,

    Jos
    Flopet17 likes this.
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: The for loop in ActionListener

    I want to make a game where a button appears randomly and you have to catch it. You have 5 levels, if you click the button x times, you advance to the next level, and so on. Till now I only have for lvl 1. But when I run the program with this code, I only see the button in the last spot.
    Java Code:
    package clickmegame2;
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class Start extends JFrame implements ActionListener{
        
        private JLabel l;
        private JButton b;
        private Dimension dl, db, center; // dl = dim label; db = dim button; center = set frame in the center of the screen;
        
        
        public Start(){
            
            //JFRAME
            setLayout(null);
            setSize(350,230);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("Catch me Game!");
            
            //PUT JFRAME IN THE MIDDLE OF THE SCREEN
            center = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(center.width/2-getSize().width/2, center.height/2-getSize().height/2);
            
            //JLABEL
            l = new JLabel("<html>"
                    + "<i> Rules of the game: </i> <br> "
                    + "Try to catch the button as fast as you can!<br>"
                    + "There are 5 levels of the game: <br>"
                    + "<i>1. Elephant(40km/h); <br>"
                    + "2. Tiger (64km/h); <br>"
                    + "3. Kangaroo (71km/h); <br>"
                    + "4. Lion (80km/h); <br>"
                    + "5. Cheetah (120km/h); <br> </i> "
                    + "To start the game click the button bellow: </p> </html>");
            
            //JBUTTON
            b = new JButton("Start!");
            
            //DIMENSION
            dl = l.getPreferredSize();
            db = b.getPreferredSize();
            
            //SETBOUNDS
            l.setBounds(20, 10, dl.width, dl.height);
            b.setBounds(120, 160, db.width, db.height);
            
            //ADD ACTIONLISTENER
            b.addActionListener(this);
            
            //ADD ELEMENTS TO FRAME
            add(l);
            add(b);
        }
        
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == b){
                setVisible(false);
                Level1 l = new Level1();
                l.setVisible(true);
            }
        }
        
    }
    Java Code:
    package clickmegame2;
    
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    public class Level1 extends JFrame implements ActionListener{
        private int score = 0;
        private JButton b;
        private Random r;
        private Dimension db, center;
        
        public Level1(){
            
            //JFRAME
            setLayout(null);
            setVisible(true);
            setSize(400,400);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("Level 1");
            
            //PUT JFRAME IN THE MIDDLE OF THE SCREEN
            center = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(center.width/2-getSize().width/2, center.height/2-getSize().height/2);
            
            //JBUTTON
            b = new JButton("Catch me!");
            b.setVisible(true);
            
            //DIMENSION
            db = b.getPreferredSize();
            
            //ADD ACTIONLISTENER
            b.addActionListener(this);
            
            //ADD BUTTON TO FRAME
            add(b);
            
            //RANDOM NUMBERS IN THE FOR
            int ran = 10;
            int ran1 = 30;
            
            //GENERATE BUTTON IN DIFFERENT PLACES
            for(int i = 0; i<100; i++)
            {
                //ran = r.nextInt(350);
                //ran1 = r.nextInt(350);
                b.setBounds(i, i, db.width, db.height);
                try {
                    Thread.sleep(100);
                }catch(Exception ex){}
            }
            
        }
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == b)
                score++;
        }
        
    }
    Java Code:
    package clickmegame2;
    
    public class ClickMeGame2 {
    
        public static void main(String[] args) {
            Start s = new Start();
            s.setVisible(true);
        }
    }
    BTW, I don't know why I get an error when I want to run the for loop with the RANDOM numbers.
    Last edited by Flopet17; 03-31-2014 at 06:43 PM.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,456
    Rep Power
    25

    Default Re: The for loop in ActionListener

    I get an error
    Please copy the full text of the error message and paste it here.
    Flopet17 likes this.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: The for loop in ActionListener

    Error:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at clickmegame2.Level1.<init>(Level1.java:50)
    at clickmegame2.Start.actionPerformed(Start.java:66)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.jav a:6505)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3311)
    at java.awt.Component.processEvent(Component.java:627 0)
    at java.awt.Container.processEvent(Container.java:222 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4861)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719 )
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:735)
    at java.awt.EventQueue.access$200(EventQueue.java:103 )
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:708)
    at java.awt.EventQueue$4.run(EventQueue.java:706)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 705)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:91)

    Please help me with the for loop in the actionListener, how can I change it?
    I'm thinking about calling the ActionListeners in the main, but the ActionEvent is void, and I don't know how to check if the button was clicked in the main, so I can go further and show the other Frame.

    Thank you

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,456
    Rep Power
    25

    Default Re: The for loop in ActionListener

    for loop in the actionListener,
    What is the loop supposed to do?

    I don't see a for loop in the actionListener? What lines of code are you talking about?

    The description of the program sounds like you want to use a Timer to move the shape around. The loop in the Level1 constructor won't have any effect until the EDT get control again. That means that only the last position of the shape will be used when the EDT displays the GUI.
    Flopet17 likes this.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    Flopet17 is offline Member
    Join Date
    Mar 2014
    Posts
    60
    Rep Power
    0

    Default Re: The for loop in ActionListener

    The loop suppose to generate the button in different places. That's why I have the setBounds, and there
    b.setBounds(i, i, db.width, db.height);
    should be

    b.setBounds(ran, ran1, db.width, db.height);
    but I get that error.

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,456
    Rep Power
    25

    Default Re: The for loop in ActionListener

    The loop suppose to generate the button in different places.
    It does change the position but the last change is the one you'll see.

    Sort of like executing these lines of code:
    x = 2;
    x = 3;
    x = 4;
    At the end you see x with a value of 4. The values of 2 and 3 are gone.

    If you want the GUI to change every so many milliseconds, use a Timer and have its action listener method make ONE change to the position of the shape and call repaint() for the GUI engine to show the shape at the new position. Every call to the Timer's listener method, change the location and call repaint() to show the new GUI.
    Flopet17 likes this.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. ActionListener
    By javalad90 in forum New To Java
    Replies: 7
    Last Post: 01-10-2014, 05:48 PM
  2. add an actionListener
    By mixpro in forum AWT / Swing
    Replies: 4
    Last Post: 12-21-2013, 02:02 PM
  3. ActionListener with for loop problem
    By pj6444 in forum AWT / Swing
    Replies: 2
    Last Post: 01-10-2013, 11:42 PM
  4. ActionListener
    By jaylimix in forum Java Applets
    Replies: 5
    Last Post: 11-06-2011, 06:05 PM
  5. Replies: 1
    Last Post: 10-01-2011, 02:12 AM

Posting Permissions

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