Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Problem with Animation and Button Action

  1. #1
    Junior Member
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Problem with Animation and Button Action

    Hello all,

    I'm new to this forum and to Java programming as well.

    I've been trying to write down a code that run a simple animation of a ball on the screen (code is added below).

    The ball itself wanders around the screen in one of four random directions (North-East, North-West, South-East, South-West) until it hits one of the panel borders or button #1 is pressed and then it changes direction.

    The animation itself works fine: when no user input is involved (just a loop) the ball wanders around and changes direction whenever it changes direction. However, the button action does not.

    Instead of changing the ball's direction, as it supposed to behave, clicking the button causes the program to freeze and not responding until the ball disappears & reappears in its new location with no animation on the way. Much as there is no-pause between the animation steps and the "repaint()" method having no effect. All there is a big delay after the button is pressed, and the ball changes it's location, rather than moving.

    What I would like the program to do is to have the button to change the course of the ball, and while the button is not pressed - the ball keeps wandering the panel independently until it reaches the next border or the button is pressed again.

    I know the program is pretty much crude, but right now I would like to cause it to work first and than temper with it.
    You can see that some lines in the code have nothing to do with what I try to achieve, while other can use a more elegant substitutions. I've all entered Println's here and there to try and find where the problem is - yet no success.

    I understand this is pretty much a long explanation, but I want to make my idea crystal clear for anyone who tries to help me. If you have any further questions - I will gladly answer.

    Yoav.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.applet.AudioClip;
    import java.io.*;
    import java.net.*;
    import java.awt.event.ItemListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.FlowLayout;
    import java.applet.*;
    import sun.audio.*;
    import java.util.ArrayList;

    public class go9 extends JFrame {
    JTextArea displayArea;
    JTextField typingArea;
    static JPanel panel;
    static Grp G1;
    JFrame frame;
    JButton button1;
    JButton button2;
    public static void main (String[] args) {
    go9 gui = new go9();
    gui.start();
    }

    public void start() {
    frame = new JFrame();
    G1= new Grp();
    frame.repaint();
    panel=new JPanel (new GridLayout(1,2));

    button1 = new JButton("Buttons #1");
    button1.addActionListener(new B1Listener());
    button2 = new JButton("Button #2");
    button2.addActionListener(new B2Listener());
    panel.add(button1);
    panel.add(button2);

    frame.getContentPane().add(G1, BorderLayout.CENTER);
    frame.getContentPane().add(panel, BorderLayout.PAGE_END);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
    frame.setSize(400,400);
    frame.setVisible(true);
    // for (int i=0; i<10; i++) {G1.run();}


    }

    class B1Listener implements ActionListener {
    public void actionPerformed (ActionEvent e) {G1.run();}
    }
    class B2Listener implements ActionListener {
    public void actionPerformed (ActionEvent e) {System.out.println(e.getID());}
    }
    }

    class Grp extends JPanel {
    static int x=100;
    static int y=100;
    int rand;
    void run() {
    if (x==0 || x==getWidth() || y==0 || y==getHeight()) {
    if (x==0) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (rand==0) {NW();}
    if (rand==1) {SW();}
    }
    if (y==0) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (rand==0) {SW();}
    if (rand==1) {SE();}
    }
    if (x==getWidth()) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (rand==0) {NE();}
    if (rand==1) {SE();}
    }
    if (y==getHeight()) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (rand==0) {NW();}
    if (rand==1) {NE();}
    }
    } else {
    rand=(int)((Math.random())*4);
    if (rand==0) {NE();}
    if (rand==1) {NW();}
    if (rand==2) {SE();}
    if (rand==3) {SW();}
    }
    }

    void SW() {
    x++;
    y++;
    while (x>0 && x<getWidth() && y>0 && y<getHeight()) {
    x++;
    y++;
    repaint();
    try {
    Thread.sleep(10);
    } catch (Exception e) {}
    }
    }

    void SE() {
    x--;
    y++;
    while (x>0 && x<getWidth() && y>0 && y<getHeight()) {
    x--;
    y++;
    repaint();
    try {
    Thread.sleep(10);
    } catch (Exception e) {}
    }
    }

    void NE() {
    x--;
    y--;
    while (x>0 && x<getWidth() && y>0 && y<getHeight()) {
    x--;
    y--;
    repaint();
    try {
    Thread.sleep(10);
    } catch (Exception e) {}
    }
    }

    void NW() {
    x++;
    y--;
    while (x>0 && x<getWidth() && y>0 && y<getHeight()) {
    x++;
    y--;
    repaint();
    try {
    Thread.sleep(10);
    } catch (Exception e) {}
    }
    }

    public void paintComponent (Graphics g) {
    //System.out.println(x+" "+this.getWidth()+" and "+y+" "+this.getHeight());
    g.setColor(Color.WHITE);
    g.fillRect(0,0,this.getWidth(),this.getHeight());

    g.setColor(Color.RED);
    g.fillOval(x,y,30,30);
    }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Problem with Animation and Button Action

    Please edit your post and wrap the code in code tags.
    See: BB Code List - Java Programming Forums - The Java Community

    Unformatted code is hard to read and understand.

  3. #3
    Junior Member
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Animation and Button Action

    PHP Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.applet.AudioClip;
    import java.io.*;
    import java.net.*;
    import java.awt.event.ItemListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.FlowLayout;
    import java.applet.*;
    import sun.audio.*;
    import java.util.ArrayList;

    public class 
    go9 extends JFrame {
    JTextArea displayArea;
    JTextField typingArea;
    static 
    JPanel panel;
    static 
    Grp G1;
    JFrame frame;
    JButton button1;
    JButton button2;
    public static 
    void main (String[] args) {
    go9 gui = new go9();
    gui.start();
    }

    public 
    void start() {
    frame = new JFrame();
    G1= new Grp();
    frame.repaint();
    panel=new JPanel (new GridLayout(1,2));

    button1 = new JButton("Buttons #1");
    button1.addActionListener(new B1Listener());
    button2 = new JButton("Button #2");
    button2.addActionListener(new B2Listener());
    panel.add(button1);
    panel.add(button2);

    frame.getContentPane().add(G1BorderLayout.CENTER);
    frame.getContentPane().add(panelBorderLayout.PAGE_END);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
    frame.setSize(400,400);
    frame.setVisible(true);
    //     for (int i=0; i<10; i++) {G1.run();}


    }

    class 
    B1Listener implements ActionListener {
    public 
    void actionPerformed (ActionEvent e) {G1.run();}
    }
    class 
    B2Listener implements ActionListener {
    public 
    void actionPerformed (ActionEvent e) {System.out.println(e.getID());}
    }
    }

    class 
    Grp extends JPanel {
    static 
    int x=100;
    static 
    int y=100;
    int rand;
    void run() {
    if (
    x==|| x==getWidth() || y==|| y==getHeight()) {
    if (
    x==0) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (
    rand==0) {NW();}
    if (
    rand==1) {SW();}
    }
    if (
    y==0) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (
    rand==0) {SW();}
    if (
    rand==1) {SE();}
    }
    if (
    x==getWidth()) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (
    rand==0) {NE();}
    if (
    rand==1) {SE();}
    }
    if (
    y==getHeight()) {
    rand=(int)((Math.random())*2);
    System.out.println(rand);
    if (
    rand==0) {NW();}
    if (
    rand==1) {NE();}
    }
    } else {
    rand=(int)((Math.random())*4);
    if (
    rand==0) {NE();}
    if (
    rand==1) {NW();}
    if (
    rand==2) {SE();}
    if (
    rand==3) {SW();}
    }
    }

    void SW() {
    x++;
    y++;
    while (
    x>&& x<getWidth() && y>&& y<getHeight()) {
    x++;
    y++;
    repaint();
    try {
    Thread.sleep(10);
    } catch (
    Exception e) {}
    }
    }

    void SE() {
    x--;
    y++;
    while (
    x>&& x<getWidth() && y>&& y<getHeight()) {
    x--;
    y++;
    repaint();
    try {
    Thread.sleep(10);
    } catch (
    Exception e) {}
    }
    }

    void NE() {
    x--;
    y--;
    while (
    x>&& x<getWidth() && y>&& y<getHeight()) {
    x--;
    y--;
    repaint();
    try {
    Thread.sleep(10);
    } catch (
    Exception e) {}
    }
    }

    void NW() {
    x++;
    y--;
    while (
    x>&& x<getWidth() && y>&& y<getHeight()) {
    x++;
    y--;
    repaint();
    try {
    Thread.sleep(10);
    } catch (
    Exception e) {}
    }
    }

    public 
    void paintComponent (Graphics g) {
    //System.out.println(x+" "+this.getWidth()+" and "+y+" "+this.getHeight());
    g.setColor(Color.WHITE);
    g.fillRect(0,0,this.getWidth(),this.getHeight());

    g.setColor(Color.RED);
    g.fillOval(x,y,30,30);
    }


  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Problem with Animation and Button Action

    Your code is still unformatted. There are no indentions at each {} pair.
    Your posted code is still all start in the left most column. It should look something like this:
     static void pyrmin(int i,int j,int x,int z)  {           
        if (i>0)     {
                System.out.print("a");
                i--;
        } else     {
                System.out.print("b");
                j++;
        }

    The indentations should be 3-4 spaces

  5. #5
    Junior Member
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Animation and Button Action

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.applet.AudioClip;
    import java.io.*;
    import java.net.*;
    import java.awt.event.ItemListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.FlowLayout;
    import java.applet.*;
    import sun.audio.*;
    import java.util.ArrayList;
     
    public class go9 extends JFrame {
    	JTextArea displayArea;
    	JTextField typingArea;
    	static JPanel panel;
    	static Grp G1;
    	JFrame frame;
    	JButton button1;
    	JButton button2;
    	public static void main (String[] args) { //launches the program.
    		go9 gui = new go9();
    		gui.start();
    	}
     
    	public void start() { //the central method - mostly what it does is to build the GUI.
    		frame = new JFrame();
    		G1= new Grp();
    		frame.repaint();
    		panel=new JPanel (new GridLayout(1,2));
     
    		button1 = new JButton("Buttons #1");
    		button1.addActionListener(new B1Listener());
    		button2 = new JButton("Button #2");
    		button2.addActionListener(new B2Listener());
    		panel.add(button1);
    		panel.add(button2);
     
    		frame.getContentPane().add(G1, BorderLayout.CENTER);
    		frame.getContentPane().add(panel, BorderLayout.PAGE_END);
     
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(400,400);
    		frame.setVisible(true);
    //		for (int i=0; i<10; i++) {G1.run();} //test loop, to find out if the animation works. The result is pleasing: when no button is involved the animation runs as it's supposed to.
     
     
    	} //end of start()
     
    	class B1Listener implements ActionListener { //inner class for button 1.
    		public void actionPerformed (ActionEvent e) {G1.run();}
    }
    	class B2Listener implements ActionListener { //inner class for button 2.
    		public void actionPerformed (ActionEvent e) {System.out.println(e.getID());}
    	}
    } //end of class go9.
     
    class Grp extends JPanel { //the class to implement the paneComponent() and the class where all the animation happens.
    	static int x=100;
    	static int y=100;
    	int rand;
    	void run() { //the central method for this class to choose the animation mode. not complete, but supposed to run on loops. everytime the ball hits the panel border or button 1 is pressed, the program goes here and changes mode.
    		if (x==0 || x==getWidth() || y==0 || y==getHeight()) { //in case the code back here and the ball hit the border.
    		if (x==0) { //in case the ball hit the left border.
    			rand=(int)((Math.random())*2);
    			System.out.println(rand);
    			if (rand==0) {NW();}
    			if (rand==1) {SW();}
    			}
    		if (y==0) { // in case the ball hit the upper border.
    			rand=(int)((Math.random())*2);
    			System.out.println(rand);
    			if (rand==0) {SW();}
    			if (rand==1) {SE();}
    			}
    		if (x==getWidth()) { // in case the ball hit right border.
    			rand=(int)((Math.random())*2);
    			System.out.println(rand);
    			if (rand==0) {NE();}
    			if (rand==1) {SE();}
    			}
    		if (y==getHeight()) { //in case the ball hit the lower border.
    			rand=(int)((Math.random())*2);
    			System.out.println(rand);
    			if (rand==0) {NW();}
    			if (rand==1) {NE();}
    			}
    		} else { //in case the ball didn't hit any of the borders yet.
    		rand=(int)((Math.random())*4); //chooses randomly a new direction.
    		if (rand==0) {NE();}
    		if (rand==1) {NW();}
    		if (rand==2) {SE();}
    		if (rand==3) {SW();}
    		}
    		}
     
    	void SW() { //the ball with go South-West.
    		x++;
    		y++; // if the ball has reached the border in the previous step, the program won't get into the following loop. therefore we will advance the ball one step toward the desired direction.
    		while (x>0 && x<getWidth() && y>0 && y<getHeight()) { //as long as the ball hasn't reached one of the borders - keep advancing the ball in that direction.
    			x++;
    			y++;
    			repaint(); //where paintComponent() is called.
    			try {
    			Thread.sleep(10);
    			} catch (Exception e) {}
    			}
    		}
     
    	void SE() { //The ball will go South-East.
    		x--;
    		y++;
    		while (x>0 && x<getWidth() && y>0 && y<getHeight()) {
    			x--;
    			y++;
    			repaint();
    			try {
    			Thread.sleep(10);
    			} catch (Exception e) {}
    			}
    		}
     
    	void NE() { //the ball will go North-East.
    		x--;
    		y--;
    		while (x>0 && x<getWidth() && y>0 && y<getHeight()) {
    			x--;
    			y--;
    			repaint();
    			try {
    			Thread.sleep(10);
    			} catch (Exception e) {}
    			}
    		}
     
    	void NW() { //The ball will go North-West.
    		x++;
    		y--;
    		while (x>0 && x<getWidth() && y>0 && y<getHeight()) {
    			x++;
    			y--;
    			repaint();
    			try {
    			Thread.sleep(10);
    			} catch (Exception e) {}
    			}
    		}
     
    	public void paintComponent (Graphics g) { // where the animation happens.
    		//System.out.println(x+" "+this.getWidth()+" and "+y+" "+this.getHeight());
    		g.setColor(Color.WHITE);
    		g.fillRect(0,0,this.getWidth(),this.getHeight());
     
    		g.setColor(Color.RED);
    		g.fillOval(x,y,30,30);
    		}
    }
    Last edited by ygeva; December 3rd, 2011 at 11:12 AM.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Problem with Animation and Button Action

    The formatted code is easier to read.
    The first thing I see is that your code in the actionPerformed takes a long time to execute. Any code you execute in an listener should be do its job quickly and return to release the GUI's thread. The repaint will not do anything until the actionPerformed method exits and returns the thread to the GUI handler.

    I don't see any comments in the code describing what your code is supposed to do. What is all the logic and methods called by the run() method supposed to do? Without a description in the code, I can not recommend what needs to be changed. The code has to stand for itself.
    Last edited by Norm; December 2nd, 2011 at 03:08 PM.

  7. #7
    Junior Member
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Animation and Button Action

    Alright. I have added comments to the code to explain the logic to it (See above).
    As I have explained - when the animation runs automatically (with no buttons involved) it runs great. But when I try to activate it by the button - it simply doesn't respond well.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    20,973
    Thanks
    51
    Thanked 2,269 Times in 2,241 Posts

    Default Re: Problem with Animation and Button Action

    If calling the run method works as you want it to, change the actionPerformed method to start a new Thread that calls the run method.
    The problem with calling the run method directly in the actionPerformed method is that that method is executing on the GUI's thread which prevents repaint() from being called until the actionPerformed method returns, which it doesn't do for several seconds while run() is executing.

  9. #9
    Junior Member
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with Animation and Button Action

    Threads. Alright, thanks. Haven't got there yet in the book, so it will take me some time. Again - thanks!

Similar Threads

  1. Blender file with animation, how to import OBJ(w/ animation) into Java?
    By cr80expert5 in forum Object Oriented Programming
    Replies: 0
    Last Post: May 12th, 2011, 03:11 AM
  2. button action problem
    By macko in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 29th, 2011, 10:51 AM
  3. Button Won't Stop Animation.
    By SyntheticD in forum What's Wrong With My Code?
    Replies: 5
    Last Post: March 24th, 2011, 02:27 PM
  4. Action button HELP?
    By utoptas in forum Java Theory & Questions
    Replies: 8
    Last Post: August 27th, 2010, 03:32 PM
  5. Action from Radio Button
    By halfwaygone in forum What's Wrong With My Code?
    Replies: 0
    Last Post: April 25th, 2010, 10:52 AM