Search code examples
java-melwuitlwuit-textarea

How to align RIGHT the content of TextArea in LWUIT?


I want to align the text in a TextArea to the right. I tried the following code:

     Form form = new Form();
     TextArea textArea = new TextArea("Some Arabic text ...");
     textArea.setRTL(true);
     textArea.setAlignment(RIGHT);
     form.addComponent(textArea);


The result was just moving the scroll to left,
But the text is still not aligned RIGHT,
check the image below:

enter image description here

So how to align the content to the RIGHT ?


Solution

  • It may sound crazy for the first instance :) but setting the alignment to TextArea.LEFT solved the issue and now it's RIGHT aligned !

        Form form = new Form();
        TextArea textArea = new TextArea("Some Arabic text ...");
        textArea.setRTL(true);
        textArea.setAlignment(TextArea.LEFT);
        form.addComponent(textArea);
    

    Setting it to LEFT makes the displayed text RIGHT aligned !

    Or by removing the textArea.setRTL(true) which is mirroring the display

        Form form = new Form();
        TextArea textArea = new TextArea("Some Arabic text ...");
        textArea.setAlignment(TextArea.RIGHT);
        form.addComponent(textArea);
    



    For those who are interested in more complicated details when it's set to RTL:
    the paint method of TextArea class is

    public void paint(Graphics g) {
        UIManager.getInstance().getLookAndFeel().drawTextArea(g, this);
    }
    

    And drawTextArea method in DefaultLookAndFeel is as follows:

    int align = ta.getAbsoluteAlignment();
    // remaining code is here in initial source
    switch(align) {
         case Component.RIGHT:
              x = ta.getX() + ta.getWidth() - rightPadding - f.stringWidth(displayText);
              break;
         // remaining code is here in initial source
    }
    g.drawString(displayText, x, y);
    

    Unfortunately TextArea.RIGHT value is 3
    But when calling ta.getAbsoluteAlignment() it returns 1 (despite that the object's alignment is set by code to TextArea.RIGHT !!)
    Meanwhile TextArea.Left value is 1
    That's why it matched the value in the switch and was aligned to RIGHT

    BTW, if you set

    textArea.setAlignment(Component.RIGHT); 
    

    it will also be wrong, because Component.RIGHT outside the paint method has the value 3 not 1 !