如何在 JTextArea 中查找光标位置

发布于 2024-10-10 09:43:33 字数 119 浏览 5 评论 0原文

有人会帮我找到 JTextArea 中以像素为单位的光标位置吗? 我使用了txtArea.getCaretPosition()。但这不是我所期望的位置。实际上我想要光标位置在像素的 x,y 坐标中。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

淡看悲欢离合 2024-10-17 09:43:33

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

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();
            }
        });
    }
}
入画浅相思 2024-10-17 09:43:33

请注意,其中一些答案返回相对于您从中获取插入符号位置的文本组件的位置。

如果您想获取插入符号在屏幕上的位置,我建议您使用以下方法:

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

aFrameYourePositioning.setLocation(p);

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);
爱冒险 2024-10-17 09:43:33

您可能必须使用 FontMetrics 类。
分析文本,找出文本的新行/换行。
然后使用

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

等等......

如果你真的想要,在这里发布你的解决方案会很酷。 :)

You may have to use the FontMetrics class.
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. :)

初见你 2024-10-17 09:43:33

就像下面一样

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

请注意该点可能为空

Just like below

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

Please be aware the point could be null

美煞众生 2024-10-17 09:43:33

我在尝试了这里的其他帖子后做了这个。只要您的文本区域禁用了文本换行,它就可以完美工作。

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

I made this one after trying the other posts here. It works perfectly as long has your textarea has text wrapping disabled.

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;
}
护你周全 2024-10-17 09:43:33
Rectangle caretRect=textPane.getUI().modelToView(textPane,textPane.getCaretPosition());

或者

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

例如;使用此矩形显示弹出窗口:

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

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

or

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

for example; use this rect for showing popup:

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

花之痕靓丽 2024-10-17 09:43:33

这是在插入符号位置显示 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);

Here is an example to display a JPopup at the caret position

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文