Swing - MaskFormatter - Enter Numbers from Right side of the textfield
Asked Answered
I

1

6

I'm new to Swing Java development. Can some one help me on this.

I have a jformattedtextfield with maskformatter. it works just fine. But only thing i would like to know is if we can make this to enter the numbers from right. The below code works just fine to enter the numbers from left to right.

Thank you for your time.

Here is the java code i have:

public class MaskFormattedTextExample extends JFrame {

    private static final long serialVersionUID = -1212313123;

    JFormattedTextField timeField;

    public MaskFormattedTextExample() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(new Dimension(200, 200));
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        MaskFormatter mask = null;
        try {
            mask = new MaskFormatter("##:##:##");
            mask.setPlaceholderCharacter('_');
        } catch (ParseException e) {
            e.printStackTrace();
        }

        timeField = new JFormattedTextField(mask);
        timeField.setHorizontalAlignment(JTextField.RIGHT);
        timeField.setCaretPosition(JTextField.RIGHT);

        getContentPane().add(timeField);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new MaskFormattedTextExample().setVisible(true);
            }
        });
    }
}
Intercommunicate answered 30/11, 2012 at 17:11 Comment(3)
Have you tried the setComponentOrientation(ComponentOrientation o) method?Deidradeidre
Component.setComponentOrientation(ComponentOrientation) FTFY @Deidradeidre :)Belisle
Thank you Brian and fireshadow52. It works good. But I see one small issue. The caret position is confusing little bit. I expect to see the caret position at the end all the time. Instead it showing at the beginning. Also I observed that the number format after I enter 3 digits 149 (I expect to see that as 1:49 but instead it showing it as 14:9)Intercommunicate
S
4

You could use:

timeField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
Spoondrift answered 30/11, 2012 at 17:16 Comment(2)
Thank you Reimeus. It works good. But I see one small issue. The caret position is confusing little bit. I expect to see the caret position at the end all the time. Instead it showing at the beginning. Also I observed that the number format after I enter 3 digits 149 (I expect to see that as 1:49 but instead it showing it as 14:9)Intercommunicate
This is the default behavior of JFormattedTextField. You could have a look at calling setCaretPosition from within a new DocumentListener registered with the component.Spoondrift

© 2022 - 2024 — McMap. All rights reserved.