In this section, we are going to display a frame where we have draw the grid. As the user move or click the cursor with the mouse over the grid, a label displays the location of cursor, i.e., shows coordinates with respect to x-axis and y-axis.
The class Point shows a location with respect to x-axis and y-axis. The BoxLayout.PAGE_AXIS displays the components in the direction that lines flow across a page. It displays the location of cursor at the end of frame. The Component.RIGHT_ALIGNMENT displays the location of cursor at the right side.
The label.setText(msg) sets the message. Then set up the window and set up the content pane. The f.show() displays the frame.
A collection of utility methods have been defined by the class SwingUtilities. The method invokeLater() executes the run() on the AWT event dispatching thread and all the AWT events have been processed.
The method drawGrid() draws a 22 x 22 grid. The class MouseEvent is used to perform mouse events (click, enter, exit) and mouse motion events (moves and drags).
Following code draws the vertical lines of the grid:
| int x = X1; while (x < X2) { g.drawLine(x, Y1, x, Y2); x += grid; } |
Following code draws the horizontal lines of the grid:
| int y = Y1; while (y < Y2) { g.drawLine(X1, y, X2, y); y += grid; } |
Here is the code of ShowCoordinates.java
import java.awt.*;
|
If you haven't click or move the cursor over the grid, output will be displayed as:

If you have click or move the cursor over the grid, output will be displayed as:

|
Recommend the tutorial |

Ask Questions? Discuss: Show Coordinates
Post your Comment