gpt4 book ai didi

java - 如何在 JTextArea 中找到光标位置

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:19:17 25 4
gpt4 key购买 nike

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

最佳答案

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

关于java - 如何在 JTextArea 中找到光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com