简体   繁体   English

如何在JTextArea中找到Cursor位置

[英]How to find Cursor position in a JTextArea

Would someone help me in finding cursor position in a JTextArea in terms of pixel? 有人会帮助我在像素方面找到JTextArea中的光标位置吗? I have used txtArea.getCaretPosition() . 我使用过txtArea.getCaretPosition() But this is not the position I expect. 但这不是我期望的立场。 Actually i want the cursor position in x,y coordinate of pixel. 其实我想要光标位置在像素的x,y坐标。

TextUI have method modelToView that'll give you position/size of the caret: TextUI有方法modelToView ,它会给你插入符号的位置/大小:

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();
            }
        });
    }
}

Note that some of these answers return the location relative to the text component you're getting the caret position from. 请注意,其中一些答案会返回相对于您从插入位置获取的文本组件的位置。

If you want to get the caret's position on the screen, I suggest you use this method: 如果你想在屏幕上看到插入符号的位置,我建议你使用这个方法:

Caret caret = yourTextComponent.getCaret();
Point p = caret.getMagicCaretPosition();
p.x += yourTextComponent.getLocationOnScreen().x;
p.y += yourTextComponent.getLocationOnScreen().y;

aFrameYourePositioning.setLocation(p);

Here is an example to display a JPopup at the caret position 以下是在插入符号位置显示JPopup的示例

Caret caret = logText.getCaret();
Point p = new Point(caret.getMagicCaretPosition());
p.x += logText.getLocationOnScreen().x;
p.y += logText.getLocationOnScreen().y;

SwingUtilities.convertPointFromScreen(p, actionsPanel);
popup.show(actionsPanel, p.x, p.y);

You may have to use the FontMetrics class. 您可能必须使用FontMetrics类。
Analyze the text, figure out the new lines / wrapping of the text. 分析文本,找出文本的新行/包装。 then use 然后用

    Font font = new Font("Verdana", Font.PLAIN, 10);  
    FontMetrics metrics = new FontMetrics(font);
    Rectangle2D bounds = metrics.getStringBounds("string", null);  
    int widthInPixels = (int) bounds.getWidth();  

etc.... 等等....

And if you really want, post your solution here to be cool. 如果你真的想要,请在这里发布你的解决方案,让它变得很酷。 :) :)

Just like below 就像下面一样

Point point = textArea.getCaret().getMagicCaretPosition();

Please be aware the point could be null 请注意,该点可能为空

I made this one after trying the other posts here. 我在这里尝试了其他帖子后做了这个。 It works perfectly as long has your textarea has text wrapping disabled. 只要您的textarea禁用了文本换行,它就能完美运行。

public Point getCaretPixelPosition(JTextArea a) {
    try {
        int cpos = a.getCaretPosition();
        Font font = a.getStyledDocument().getFont(a.getStyledDocument().getLogicalStyle(cpos));
        FontMetrics metrics = getFontMetrics(font);

        int lineNum = a.getLineOfOffset(cpos);
        int y = lineNum * metrics.getHeight();
        int lineStart = a.getLineStartOffset(lineNum);
        int x = metrics.stringWidth(a.getText().substring(lineStart, cpos));

                    return new Point(x,y);

    } catch(BadLocationException e) {}
    return null;
}
Rectangle caretRect=textPane.getUI().modelToView(textPane,textPane.getCaretPosition());

or 要么

Rectangle caretRect=textPane.modelToView(textPane.getCaretPosition());

for example; 例如; use this rect for showing popup: 使用此rect显示弹出窗口:

popupMenu.show(textPane, caretRect.x, caretRect.y); popupMenu.show(textPane,caretRect.x,caretRect.y);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM