Would someone help me in finding cursor position in a JTextArea in terms of pixel?
I have used txtArea.getCaretPosition()
. But this is not the position I expect. Actually i want the cursor position in x,y
coordinate of pixel.
Answer: Use the jQuery event. pageX and event. pageY pageX and event. pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.
Remove all whitespace between <textarea></textarea> or <input></input> tags. Or in your css code you have text-align: center to your parent elements, or somewhere else but its still formating your input. Press f12 in the browser and check the element. Save this answer.
Constructs a new TextArea. A default model is set, the initial string is null, and rows/columns are set to 0.
JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit the text .
TextUI have method modelToView
that'll give you position/size of the caret:
import java.awt.BorderLayout;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
public class PixelPositionOfCaretDemo
{
public PixelPositionOfCaretDemo()
{
JLabel label = new JLabel("Move the caret...");
JTextArea area = new JTextArea();
area.addCaretListener(new MyCaretListener(label));
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBounds(new Rectangle(400, 400, 400, 400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(area, BorderLayout.CENTER);
frame.add(label, BorderLayout.SOUTH);
frame.setVisible(true);
}
private static class MyCaretListener implements CaretListener
{
private final JLabel label;
MyCaretListener(JLabel label)
{
this.label = label;
}
@Override
public void caretUpdate(CaretEvent e)
{
JTextComponent textComp = (JTextComponent) e.getSource();
try
{
Rectangle rect = textComp.getUI().modelToView(textComp, e.getDot());
label.setText(rect.toString());
}
catch (BadLocationException ex)
{
throw new RuntimeException("Failed to get pixel position of caret", ex);
}
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new PixelPositionOfCaretDemo();
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With