当文本从右到左时,确定JTextArea的某个区域中存在哪些文本



我有一些代码,它试图确定文本区域的给定垂直切片内的文本,其中垂直切片被指定为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(
"u05D4u05D5u05D3u05E2u05EA u05D8u05D9u05D9u05D2u05E8 " +
"u05D8u05E7u05E1u05D8 u05D1u05E2u05D1u05E8u05D9u05EA");
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

惊喜点:

  1. 最靠近左上角的字符不是字符0
  2. 最靠近右上角的字符不是字符0
  3. 最接近字符0位置的字符不是字符0

在代码中添加以下行:

textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

您的输出数字将发生变化,但您的文本将显示在文本区域的右侧。我希望这是你想要的。

编辑:

根据这一点,希伯来语和阿拉伯语应该是RT方向。

最新更新