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 10 of 10

Thread: Help with Java Thread for animation

  1. #1
    Junior Member
    Join Date
    Jul 2014
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help with Java Thread for animation

    My assignment is to change my program that animates race cars using a timer based on speed entered into text fields, to a program that uses threads to control the animation.

    This is the problem I'm having: I do not fully understand how threads are implemented into code and where, but my program only works for two cars - sometimes one. Also, in the console I get NullException errors.

    I would like to know how to properly code Java using threads to control the animation.
    Attached Files Attached Files


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Help with Java Thread for animation

    Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for new members.

    Users prefer to see relevant code posted properly as described at the above link.

    Swing is not thread safe. Sometimes mixing threads and Swing works, sometimes it doesn't. One way to ensure the mixing won't work is to use a while ( true ) loop with a Thread.sleep() to control the application's action.

    The other preferred, recommended, correct approach is to use a javax.swing.Timer to control animation in a Swing app. There are at least 2 ways I can think of to accomplish what you're trying to do; one is with multiple Timers (one for each car), the other with just one. Either way, successfully moving one of the cars with one Timer is a start, so try that and come back.

  3. #3
    Junior Member
    Join Date
    Jul 2014
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Java Thread for animation

    Well it wasn't a lot of code, but okay thank you.

  4. #4
    Junior Member
    Join Date
    Jul 2014
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Did I do this right? First timer with threads.(no pun intended)

    Everything runs fine, but I'm fairly new to Java and wanted to get some opinions.

    Overview: This program is an animation of four racing cars - the speed is set by the user(no less than 1 or greater than 5). Initially using a timer with a private class to fire a fixed rate, our assignment was to use threads.

    Did I implement thread usage correctly to control the car animation?

    What can I do to improve my code to increase performance, effectiveness, or anything in general?


    Looking forward to your responses!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.FlowLayout;
    import javax.swing.border.*;
    import java.awt.event.*;
     
    public class RaceCarsThread extends JApplet {
     
    	//create a new car object
    	private final DrawCar car1 = new DrawCar();
    	private DrawCar car2 = new DrawCar();
    	private DrawCar car3 = new DrawCar();
    	private DrawCar car4 = new DrawCar();
     
    	//create textfields for each car for the users to specify their speed
    	private final JTextField jtfSpeed1 = new JTextField(5);
    	private final JTextField jtfSpeed2 = new JTextField(5);
    	private final JTextField jtfSpeed3 = new JTextField(5);
    	private final JTextField jtfSpeed4 = new JTextField(5);
     
     
    	//creates a button labeled "start" to initiate the race
    	private final JButton jbtStart = new JButton("Start");
     
    	//stores the input for the speed of each car
    	private int carSpeed1;
    	private int carSpeed2;
    	private int carSpeed3;
    	private int carSpeed4;
     
            private Thread animator;
     
     
    	public RaceCarsThread() {
     
     
    		// Creates the top panel of the applet which stores holds the text fields for each car
    		// along with the start button to begin the race.
    		JPanel p1 = new JPanel();
    		p1.setLayout(new FlowLayout(FlowLayout.CENTER));
    		p1.add(new JLabel("Car 1:"));
    		p1.add(jtfSpeed1);
    		p1.add(new JLabel("Car 2:"));
    		p1.add(jtfSpeed2);
    		p1.add(new JLabel("Car 3:"));
    		p1.add(jtfSpeed3);
    		p1.add(new JLabel("Car 4:"));
    		p1.add(jtfSpeed4);
     
     
     
    		//sets the layout of the overall applet window
    		setLayout(new GridLayout(6, 1));
    		add(p1); //adds the first panel to the top of the window
                    add(jbtStart);
    		add(car1); // adds the first car to the window
    		add(car2); // adds the second car to the window
    		add(car3); // adds the third car to the window
    		add(car4); // adds the fourth car to the window
     
     
     
     
    	}
     
    	public static void main(String[] args) {
    		JFrame frame = new JFrame("Racing Cars");
    		RaceCarsThread applet = new RaceCarsThread();
    		frame.add(applet);
     
    		frame.setSize(800, 350);
    		frame.setLocationRelativeTo(null);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
                    frame.setVisible(true);
                    applet.startCars();
     
                    }
                     public void startCars() {
     
    		// listens for the start button to be clicked
    		jbtStart.addActionListener(new ActionListener() {
     
     
                            @Override
    			public void actionPerformed(ActionEvent event) {
     
     
    				carSpeed1 = Integer.parseInt(jtfSpeed1.getText());
                                    carSpeed2 = Integer.parseInt(jtfSpeed2.getText());
                                    carSpeed3 = Integer.parseInt(jtfSpeed3.getText());
                                    carSpeed4 = Integer.parseInt(jtfSpeed4.getText());
     
     
     
    				//to ensure that the speed of the car doesn't exceed the specified range of 1 to 5 
    				if (carSpeed1 > 5) {
    					carSpeed1 = 5; //if the user picks a number higher than 5 set the speed to 5
    				} else if (carSpeed1 < 1) {
    					carSpeed1 = 1; //if the user picks a number lower than 1 set the speed to 1
    				}
     
    			}
                        });
                     }  
     
    	class DrawCar extends JPanel implements Runnable {
                    private Thread timer = new Thread(this);
    		private int xOrigin = 0; // holds the x coordinate of the car
     
    		public DrawCar() 
                    {
                        timer.start();
     
     
    			setBorder(new LineBorder(Color.black, 2)); //draw a black line around the border of each cell that holds the car
     
                    }
                    @Override
                    public void run(){
                                    try {
            while (true) {
              repaint();
              Thread.sleep(10);
            }
          }
          catch (InterruptedException ex) {
          }
        }
     
     
                    @Override
    		protected void paintComponent(Graphics g) {
    			super.paintComponent(g);
     
    			// Create a Polygon object
    			Polygon rectanglePolygon = new Polygon();
    			Polygon trapezoidPolygon = new Polygon();
     
    			// Add points to the tapazoidPolygon
    			trapezoidPolygon.addPoint((xOrigin + 40), 18);
    			trapezoidPolygon.addPoint((xOrigin + 30), 18);
    			trapezoidPolygon.addPoint((xOrigin + 20), 30);
    			trapezoidPolygon.addPoint((xOrigin + 50), 30);
    			// Set the color for the trapezoid to red and fill in the
    			// polygon
    			g.setColor(Color.RED);
    			g.fillPolygon(trapezoidPolygon);
     
    			// Add points to the rectanglePolygon
    			rectanglePolygon.addPoint((xOrigin + 10), 30);
    			rectanglePolygon.addPoint((xOrigin + 10), 41);
    			rectanglePolygon.addPoint((xOrigin + 60), 41);
    			rectanglePolygon.addPoint((xOrigin + 60), 30);
    			// Set the color for the rectangle to green and fill in the
    			// polygon
    			g.setColor(Color.GREEN);
    			g.fillPolygon(rectanglePolygon);
     
    			// Draw the circles for the wheels of the car
    			g.setColor(Color.BLACK);
    			g.fillOval((xOrigin + 20), 41, 10, 10);
    			g.fillOval((xOrigin + 40), 41, 10, 10);
     
                            car1.xOrigin += carSpeed1; //increase the position of the car by what number the user specified as the speed
    			car2.xOrigin += carSpeed2;
                            car3.xOrigin += carSpeed3;
                            car4.xOrigin += carSpeed4;
     
     
                            if(car1.xOrigin > 800 && car2.xOrigin > 800 
                                    && car3.xOrigin > 800 && car4.xOrigin > 800)
                            {
     
                               carSpeed1 = 0;
                               carSpeed2 = 0;
                               carSpeed3 = 0;
                               carSpeed4 = 0;
     
                                car1.xOrigin = 0;
     
                                car2.xOrigin = 0;
     
                                car3.xOrigin = 0;
     
                                car4.xOrigin = 0;
     
     
     
     
                            }
     
                        }
    		}
     
     
     
    }
    Last edited by Phil Program; July 6th, 2014 at 08:18 AM. Reason: Clarity

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Java Thread for animation

    Threads merged.

    Is this an applet or a desktop program? It extends JApplet AND has a main() method. They don't go together.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Jul 2014
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Java Thread for animation

    Quote Originally Posted by Norm View Post
    Threads merged.

    Is this an applet or a desktop program? It extends JApplet AND has a main() method. They don't go together.
    Well...this is embarrassing, but it was an assignment that was supposed to be an applet. But I'm new to Java - I went from Objecct Oriented C++ to Advanced Java, so I have no foundation.

    It doesn't make a difference though in terms of the threads though does it? How can I make it just a desktop program, and how can I make it just an applet though

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Java Thread for animation

    The GUI can be handled in a JPanel and that JPanel can be displayed in a applet or in a desktop JFrame.

    See the tutorial for how to code an applet: Lesson: Java Applets (The Java™ Tutorials > Deployment)
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Jul 2014
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Java Thread for animation

    Great - the main point though - is the program running okay with the threads? My assignment is for the threads to control animation.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with Java Thread for animation

    It works for me.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10

    Default Re: Help with Java Thread for animation

    Make a class to represent an oval. Make two instances. Give the two instances different angular velocities. Currently because you increment degrees by 1.0 every 25 ms you have an angular velocity fixed at 40 degrees per second. If each oval has its own degrees field and you increment the two by different amounts, the ovals will rotate at different rates.

Similar Threads

  1. Moving from Animation to JAVA programmer
    By nitin_hbk in forum Member Introductions
    Replies: 3
    Last Post: February 1st, 2014, 09:59 AM
  2. How to categorise a daemon thread to specific thread in java?
    By rajasekhar_b in forum What's Wrong With My Code?
    Replies: 0
    Last Post: January 10th, 2014, 07:55 AM
  3. Java animation code
    By MW130 in forum What's Wrong With My Code?
    Replies: 16
    Last Post: January 17th, 2013, 01:53 PM
  4. Java animation using pictures help
    By NekoSH0GUN in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 1st, 2011, 11:49 AM
  5. 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