问题
I am trying to force a JTextArea (and other text components through my application) to allow users to type RTL. This works correctly for input such as Arabic, but I must also be able to set it to apply this to standard text. Therefore, if I type "hello!" it will show up as "!olleh".
I have tried using the applyOrientation() method and setting the text area to have RTL like so:
jTextPane1.getDocument().putProperty(
TextAttribute.RUN_DIRECTION,
TextAttribute.RUN_DIRECTION_RTL);
I have had no success thus far. It has been suggested that I try the Bidi libraries, but these seem focused on interpretation of text which is already bidirectional. When I apply the above, I get right justified text, but it remains LTR in terms of the character order. Is there anything that I'm missing here? Is there a way to set the value that Java itself checks when looking for which direction text entry should move the carat?
回答1:
What about component orientation?
boolean rtl = true;
t_text.setComponentOrientation(rtl ?
ComponentOrientation.RIGHT_TO_LEFT :
ComponentOrientation.LEFT_TO_RIGHT);
what you said about hello! and !olleh nothing like this will happen :) this is reverse not right-to-left. RTL of I am Soley! is !Soley am I which it shows words starting from right to left.
By the way, use a JTextPane instead of JTextArea, JTextArea I believe does not support RTL. That's what I read somewhere when I wanted to make JtextPane RTL once.
Well, if you want to reverse the input string, use:
public static String getReverse(String str) {
return new StringBuffer(str).reverse().toString();
}
However, if you want to reverse all words, then split them after you reversed the whole input:
String[] list = getReverse("I am soley!").split(" ");
String[] ret = new String[list.length];
int len = list.length;
for(String w:list){
ret[--len] = s;
}
list = null;
// you have your words reversed in ret array
回答2:
My problem was solved by the \u202e and the \u202c characters pointed out by RealSkeptic. One will force all characters following it into RTL form, the other forces all characters following it into LTR form. This is a quick and dirty fix, but for my problem, it offered the solution I needed.
来源:https://stackoverflow.com/questions/30579798/forcing-rtl-order-in-a-jtextarea