Wrong behavior in concatenation of strings when allignment of component is "RIGHT_TO_LEFT"

StackOverflow https://stackoverflow.com/questions/17947874

سؤال

private JTextField resultTextField = new JTextField("0");
resultTextField.setFont(textFieldFont);
        resultTextField.setBounds(COMMON_X, COMMON_Y, 180, 50);
        resultTextField.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        add(resultTextField);

I have created a JTextField as above.My application consists of number buttons and '.'. When I click on number buttons they get appended right (i.e. "5" on 5 click and then "52" on 2 click). But on clicking the '.' button the expected result is "5." but the it is displayed as ".5" and then on clicking "2" , "5.2" is displayed. Where could I be going wrong?

هل كانت مفيدة؟

المحلول

I'm guessing (from your tags) that you're programming a calculator of some sort and that you want to achieve right-aligned text, not right-to-left-oriented text. Right-to-left orientation is used for e.g. arabic languages, which are written (you guessed it) from right to left, instead of the "western" way of writing from left to right.

I suggest you remove the applyComponentOrientation() and look at setHorizontalAlignment instead.

PS: that being said, I can't really tell why '5'+'.' is '.5', but '5'+'.'+'2' is displayed as '5.2'.

نصائح أخرى

I got interested, and produced the following SSCCE:

import java.awt.ComponentOrientation;

import javax.swing.JFrame;
import javax.swing.JTextField;


public class BasicFrame extends JFrame
{
    public static void main(String[] args)
    {
        BasicFrame frame = new BasicFrame();
        frame.go();
    }

    private void go()
    {
        JTextField resultTextField = new JTextField("0");
        resultTextField.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        add(resultTextField);
        pack();
        setVisible(true);
    }

}

So now I have the same question: If I clear the field and enter "123", it appears as "123"; when I click the period key (either of them), the field then shows ".123"; if I then enter "abc", the field shows "123.abc"; the period jumps to the right of the displayed string when I enter the 'a'. This does not follow what a former boss of mine called the "principle of least atstonishment"...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top