有人会帮我找到 JTextArea 中以像素为单位的光标位置吗?
我用过txtArea.getCaretPosition()
。但这不是我所期望的位置。实际上我想要光标位置在x,y
像素坐标。
TextUI http://download.oracle.com/javase/6/docs/api/javax/swing/plaf/TextUI.html有方法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();
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)