我有一些代码试图确定文本区域的给定垂直切片中的文本是什么,其中垂直切片被指定为Y坐标而不是线.
顺便说一下,转换为使用线数学是这个问题的一个很好的解决方法,所以这就是我将要使用的,但是我可以设想你可能只有Y坐标的情况,它看起来像这样的东西会出现,所以无论如何我都会问它.
我把我的问题简化为一个相当简约(lol Java)的例子.我们显示带有一些文本的框架,然后尝试确定最接近文本区域开头的文本的字符偏移量.我们从常识中知道它将为0,但是以编程方式解决问题就是问题.
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new RtlTest().run();
}
});
}
JFrame frame;
JTextArea textArea;
public void run() {
textArea = new JTextArea(
"הודעת טייגר " +
"טקסט בעברית");
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
measure();
}
});
}
public void measure() {
try {
System.out.println("Either the line is left to right or it's right to left " +
"(or a mix), so one of these two values should be 0:");
System.out.println(textArea.viewToModel(new Point(0, 0)));
System.out.println(textArea.viewToModel(new Point(textArea.getWidth() - 1, 0)));
Rectangle firstLetterView = textArea.modelToView(0);
System.out.println("This one should definitely be 0, right? " +
"I mean, we got the coordinates from Swing itself:");
System.out.println(textArea.viewToModel(new Point(firstLetterView.x,
firstLetterView.y)));
frame.dispose();
} catch (BadLocationException e) {
throw new IllegalStateException(e);
}
}
输出相当令人惊讶:
Either the line is left to right or it's right to left (or a mix),
so one of these two values should be 0:
23
23
This one should definitely be 0, right? I mean, we got the coordinates from Swing itself:
24
惊喜点:
>最靠近左上角的字符不是字符0.
>最靠近右上角的字符不是字符0.
>最接近字符0位置的字符不是字符0.