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

Thread: Question about Program Output

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

    Default Question about Program Output

    Hello,

    a) I have a Ball Object which implements the Runnable interface and traces the various positions of a ball.

    b) I then have a Ball_Bounce JPanel inside a JFrame which creates two instances of the Ball object and then paints them to the JPanel.

    As per my understanding, when the main() program in Ball_Bounce.java is started, there a total of three threads running in this program, one for each ball and one for the main(). What I cannot understand is whenever the balls collide, I end up getting the "Collision" message twice even though the collision is checked only in the main() thread.

    I would be grateful for an explanation for why I am getting the collision message outputted twice.

    Thank you!

    [#]public class Ball implements Runnable
    {
        private boolean xUp, yUp, xUp1, yUp1;
        private int x, y, xDx, yDy;
        private final int MAX_X = 500, MAX_Y = 500;
        private boolean flag = true;
        private static Thread ball;
     
     
        public  Ball(int xCoordinate, int yCoordinate)
        {
            x = xCoordinate;
            y = yCoordinate;
            xUp = false;
            yUp = false;
            xDx = 1;
            yDy = 1;
     
            ball = new Thread(this);
            ball.start();
     
        }
     
        public int getX()
        {
            return x;
        }
     
        public int getY()
        {
            return y;
        }
     
        public void run()
        {
            while ( flag == true )
            {
                try
                {
                    ball.sleep(12);
                }
                catch ( InterruptedException exception )
                {
                    System.err.println( exception.toString() );
                }
     
                if ( y <= 0 ) {
                    yUp = true;
                    yDy = ( int ) ( Math.random() * 5 + 2 );
                }
     
                else if ( y >= MAX_Y - 50 ) {
                    yDy = ( int ) ( Math.random() * 5 + 2 );
                    yUp = false;
                }
     
                if ( x <= 0 ) {
                    xUp = true;
                    xDx = ( int ) ( Math.random() * 5 + 2 );
                }
     
                else if ( x >= MAX_X - 50 ) {
                    xUp = false;
                    xDx = ( int ) ( Math.random() * 5 + 2 );
                }
     
     
                if ( xUp == true )
                    x += xDx;
                else
                    x -= xDx;
     
                if ( yUp == true )
                    y += yDy;
                else
                    y -= yDy;
     
     
            }
        }
     
     
    }[/#]----------------------------------------------------------------------------------------------------------------------------------------------
    [#]import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.lang.Thread;
     
    public class Ball_Bounce extends JPanel implements ActionListener
    {
        private Ball ball[] = new Ball[2];
        private Timer timer;
        private int count = 0;
     
        public Ball_Bounce()
        {
            timer = new Timer (12, this);
            timer.start();
            ball[0] = new Ball( 300, 250);
            ball[1] = new Ball (450, 450);
     
        }
     
        public void actionPerformed (ActionEvent e)
        {
            repaint();
        }
     
        public void paintComponent( Graphics g )
        {
            super.paintComponent(g);
     
            for (int i = 0; i < 2; i++)
            {
                if (i == 0)
                {
                    Color c = Color.RED;
                    g.setColor (c);
                    g.fillOval( ball[i].getX(), ball[i].getY(), 50, 50 );
                }
                if ( i == 1)
                {
                    Color c = Color.BLUE;
                    g.setColor (c);
                    g.fillOval( ball[i].getX(), ball[i].getY(), 50, 50 );
                }
     
            }
            if (Math.abs(ball[0].getX()-ball[1].getX()) <= 50 && Math.abs(ball[0].getY()-ball[1].getY()) <= 50)
            {
                 JOptionPane.showMessageDialog (null, "Collision");  
            }
        }
     
        public static void main (String args [])
        {
            JFrame f = new JFrame ("Bouncing Ball");
            Ball_Bounce b = new Ball_Bounce ();
            f.add (b);
            f.setSize (500,500);
            f.setVisible(true);
        }
     
    }[/#]


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Question about Program Output

    Declaring variables as static means there is only one value that is used by all instances of the class.


    There should NOT be long running tasks in the paintComponent() method.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Question about Program Output

    Quote Originally Posted by hopp22 View Post
    I would be grateful for an explanation for why I am getting the collision message outputted twice.
    But before, you should understand that your code has several flaws.

    1) the x / y variables are written in the context of your ball-thread and are read in the context of the EDT (Event Dispatch Thread). Without explicit precautions, in general there is no absolute guarantee that the EDT always "sees" up-to-date values.

    2) never, I repeat, never open windows/dialogs/options-panes or change layouts into a paint/paintComponent !

    3) the tecnique to use a Timer with a timing that is "similar" to the sleep into the threads, is rather rough and in general is not a good/common approach.

    There are other minor mistakes that, however, don't prevent the compilation.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

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

    Default Re: Question about Program Output

    Swing is not thread safe. Animation in Swing is done using javax.swing.Timer. You can find many examples on the Internet that use Timer to do animation in Swing. Start simple and grow from there.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Question about Program Output

    Also posted at: Question about Threads/Events
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Very easy question about output.
    By ma5sacre in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 11th, 2014, 10:12 AM
  2. My program always gives me an output of 0.0, what's wrong with it?
    By thepiranha in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 31st, 2013, 12:29 AM
  3. I/O Program output error
    By gatorsgirl in forum File I/O & Other I/O Streams
    Replies: 8
    Last Post: April 11th, 2012, 04:18 PM
  4. Question about formatting output
    By mwr76 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 10th, 2011, 11:57 AM
  5. No Output in Program:
    By bengregg in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 17th, 2011, 11:01 PM