简体   繁体   English

如何使用Java在任何应用程序中插入符的位置?

[英]How to get caret position inside any application using Java?

It seemed to be such a simple question, but after a long time researching the topic, I am still not able to find any answer to this. 这似乎是一个简单的问题,但是经过长时间的研究,我仍然找不到任何答案。 Using Java, I want to display a small tooltip next to a caret (text cursor) position. 使用Java,我想在插入符号(文本光标)位置旁边显示一个小的工具提示。 I need to caret position inside any application. 我需要在任何应用程序中插入符号的位置。 That means if I open Word, Notepad, Chrome browser and I start typing I need to see X & Y of the cursor. 这意味着,如果我打开Word,记事本,Chrome浏览器并开始输入内容,则需要查看光标的X和Y。 Any way to do this using Java? 使用Java可以做到这一点吗? I've seen implementations in C# on CodeProject, but I need to do this in java. 我已经在CodeProject上看到了C#中的实现,但是我需要在java中实现。

Basically use the .getMagicCaretPosition() function: 基本上使用.getMagicCaretPosition()函数:

import java.awt.Dimension;
import java.awt.Point;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.Caret;
public class CaretPos implements Runnable
{
    JFrame frame;
    JPanel panel;
    JTextPane tPane;
    Caret newCaret;
    Point point;

    @Override
    public void run() {
        frame = new JFrame("CaretPos");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel = new JPanel();
        tPane = new JTextPane();
        newCaret = tPane.getCaret(); // you probably dont need to create another
                                     // Caret, but i did anyway to add the listener
        newCaret.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                point = newCaret.getMagicCaretPosition();
                System.out.println(point);
            }
        });
        tPane.setCaret(newCaret);
        tPane.setPreferredSize(new Dimension(500,500));
        panel.add(tPane);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        CaretPos run = new CaretPos();
        SwingUtilities.invokeLater(run);
    }

}

I used a JTextPane, but im sure other swing components can be used 我使用了JTextPane,但是我确定可以使用其他swing组件

EDIT: Sorry I totally misunderstood your question. 编辑:对不起,我完全误解了你的问题。 I thought you wanted to find the caret position in ANY of YOUR programs. 我以为您想在任何程序中找到插入符号的位置。 My bad. 我的错。

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

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