1. Place a JLabel tag at the top of the window. The text in the tag defaults to "The coordinates of the right-click mouse are displayed here"
2. Add a mouse event to the Jframe window. When the mouse right clicks on the window, the mouse coordinates are displayed in the JLabel tag.
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 coordinates of the form JLabel lb = new JLabel("The coordinates after right-clicking the mouse are displayed"); // Create a Label object jf.add(lb); // Add a label to the window jf.addMouseListener(new MouseListener() { //Add a mouse event listener for the window @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub if(e.getButton()==e.BUTTON3){ // Determine whether the obtained button is the right click of the mouse lb.setText(e.getX()+","+e.getY()); // Get the coordinates of the mouse click 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 mouseEntered(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 operation results are as follows:
Java obtains the position coordinate instance of the mouse clicking on Jframe, which is very simple and easy to understand, I hope it will be helpful to beginners