Search code examples
javaacm-java-libraries

Using break to stop the moving lines in java


I am completely new to java and I have one problem I am trying to resolve. I am using ACM Library for my purpose. My goal is the following:

  1. Move Label 1
  2. Move Label 2
  3. Compare label 1's and label 2's position (when the text hits and its on each other) "Using 'if' statement"
  4. Once on top, stop it by using break statement.
  5. Restart the cycle.

If someone could help me out by explaining how this can be implemented. That would be awesome. I am trying to learn. Thank you!

import acm.graphics.GLabel;
import acm.program.CommandLineProgram;
import acm.program.GraphicsProgram;

public class Main extends GraphicsProgram {

    public void run( )

    {
            int label1_xy = 50;
            int label2_xy = 200;

            GLabel label1 = new GLabel("Hello World.");
            add(label1, label1_xy,label1_xy);

            GLabel label2 = new GLabel("Goodbye World.");
            add(label2, label2_xy,label2_xy);

            while (true)
            {
            label1.move(10,10);
                pause(500);
            label2.move(-10,-10);
            break;
            }
    }
}

Solution

    1. Move Label 1
    2. Move Label 2

    You have done these two.

    1. Compare label 1's and label 2's position (when the text hits and its on each other) "Using 'if' statement"
    2. Once on top, stop it by using break statement.

    You can compare the position of those two labels by trying to retrieve the "bound" of the object. example :

    label1.move(10,10);
    pause(500);
    if (label1.getBounds().getX() == label2.getBounds().getX() 
         && label1.getBounds().getY() == label2.getBounds().getY()) {
        break;
    } else {
        label2.move(-10,-10);
    }
    
    1. Restart the cycle

    You can restart this by putting another while block for the run() code or maybe just call the run() (beware of the StackOverflowError here).