An example of super simple java getting the coordinates of the mouse and clicking the coordinates (the coordinates of the mouse on the Jframe), click the jframe
1. Place a JLabel label at the top of the window. The text in the label is "show the coordinates of right-click" by default"
2. Add a mouse event to the Jframe window. When you right-click the window, the coordinates of the mouse are displayed in the JLabel label.
Java code implementation
Import java. awt. flowLayout; import java. awt. event. mouseEvent; import java. awt. event. mouseListener; import javax. swing. JFrame; import javax. swing. JLabel; public class Jframe_1 {public static void main (String [] args) {JFrame jf = new JFrame ("Jframe"); jf. setLayout (new FlowLayout (); jf. setSize (300,200); // set the width and height of the form jf. setVisible (true); // set the window to visible jf. setLocation (800,200); // set the JLabel lb = new JLabel ("the coordinates after right-clicking") of the form; // create a Label object jf. add (lb); // add the tag to the window. addMouseListener (new MouseListener () {// Add a mouse event listener @ Override public void mousePressed (MouseEvent e) {// TODO Auto-generated method stub if (e. getButton () = e. BUTTON3) {// determine whether the retrieved button is right-click lb with the mouse. setText (e. getX () + "," + e. getY (); // obtain the coordinates of the mouse clicking position and send it to the text of the label }}@ Override public void mouseClicked (MouseEvent e) {// TODO Auto-generated method stub} @ Override public void mouseReleased (MouseEvent e) {// TODO Auto-generated method stub} @ Override public void mouseEntered (MouseEvent e) {// TODO Auto-generated method stub} @ Override public void mouseExited (MouseEvent e) {// TODO Auto-generated method stub }});}}
The running result is as follows:
The example of java getting the coordinates of the locations clicked by the mouse on the Jframe is very easy to understand. It is helpful for beginners.