How to Use X and Y Coordinates in Java
The Java programming language has a rich library of functions that are useful for addressing general programming needs. Within this library is the Point class, which holds an X and a Y coordinate. If you are using 2D graphics or performing calculations involving the coordinate plane, you will need to familiarize yourself with the Point class. The class is fairly straightforward and you should be able to get up and running in very little time.
Things You'll Need
- Java Software Development Kit with NetBeans Integrated Development Environment (IDE) Bundle
Instructions
-
-
1
Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Application" from the list on the right-hand side of the screen. A new source code file appears in the NetBeans text editor window. The source code file contains an empty main function, which is where most of your source code will go.
-
2
Import the Points class by writing the following line at the top of the source code file:
import java.awt.Point;
-
-
3
Create a new point and set its coordinates to X = 23 and Y = 42. You can do this by writing the following line of code within the curly brackets of the main function:
Point p = new Point(23, 42);
-
4
Create a new point and set its location to the location of the point created in the previous step using the getLocation() method. Write the following line after the line written in the previous step to accomplish this:
Point x = p.getLocation();
-
5
Move the point to some arbitrary location on the 2D plane using the move() method. For example, to move the point to X = 5, Y =15, you could write the following:
x.move(5, 15);
-
6
Print out the X and Y coordinates of your Point using the getX() and getY() methods, like this:
System.out.println(x.getX());
System.out.println(x.getY());
-
7
Execute the program by pressing the F6 key. The program output looks like this:
5
15
-
1