Header Ads Widget

Responsive Advertisement

Ticker

6/recent/ticker-posts

Get current cursor location in JTextArea (Java)

Complete source code below will show you, how to get current cursor location in JTextArea.

***********************************************************************
COMPLETE SOURCE CODE FOR : GetCurrentCursorLocationInJTextArea.java
***********************************************************************
import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class GetCurrentCursorLocationInJTextArea extends JTextArea implements MouseMotionListener
{
//Create window using JFrame with title ( Get current cursor location in JTextArea )
JFrame frame=new JFrame("Get current cursor location in JTextArea");

//Create text field that will show you, current cursor location
JTextField textFieldX=new JTextField(5);
JTextField textFieldY=new JTextField(5);

//Create label that will use to describe function for each text field
JLabel labelX=new JLabel("Coordinate X : ");
JLabel labelY=new JLabel("Coordinate Y : ");

//Create panel that will use to store text field and label
JPanel panelX=new JPanel();
JPanel panelY=new JPanel();

//Panel that will use to store panelX and panelY
JPanel container=new JPanel();

public GetCurrentCursorLocationInJTextArea()
{
 //Add mouse motion listener to JTextArea
 addMouseMotionListener(this);

 //Set container layout using BorderLayout
 container.setLayout(new BorderLayout());

 //Set panelX and panelY layout using GridLayout
 panelX.setLayout(new GridLayout(1,2));
 panelY.setLayout(new GridLayout(1,2));

 //Add labelX and textFieldX into panelX
 panelX.add(labelX);
 panelX.add(textFieldX);

 //Add labelY and textFieldY into panelY
 panelY.add(labelY);
 panelY.add(textFieldY);

 //Add panelX and panelY into container
 container.add(panelX,BorderLayout.WEST);
 container.add(panelY,BorderLayout.EAST);

 //Set frame layout using BorderLayout
 frame.setLayout(new BorderLayout());

 //Add JTextArea  into JFrame
 frame.add(this,BorderLayout.CENTER);

 //Add container into JFrame
 frame.add(container,BorderLayout.SOUTH);

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(500,500);
 frame.setVisible(true);
}

public void mouseMoved(MouseEvent event)
{
 //Get current X-coordinate for cursor
 textFieldX.setText("");
 textFieldX.setText(Integer.toString(event.getX()));

 //Get current Y-coordinate for cursor
 textFieldY.setText("");
 textFieldY.setText(Integer.toString(event.getY()));
}

public void mouseDragged(MouseEvent event)
{
 //Do nothing because our case not handle dragging
}

public static void main(String[]args)
{
 GetCurrentCursorLocationInJTextArea gcclijta=new GetCurrentCursorLocationInJTextArea();
}
}

***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************