Search code examples
javaregexswingjtextfield

Validate JTextField value so that it starts with "RA" then has 8 digits


I have a JTextField where in the user has to input the data. Its value has to always start with RA and must have exactly 8 digits after it. So, its length will be 10 always. for e.g., RA12345678.

How do I do this in Java?

I tried using MaskFormatter and JFormattedTextField but, did not achieve the results. I need to validate the input with length together.


Solution

  • I'd use a JSpinner for this, and simply prefix RA to the number. E.G.

    Image

    enter image description here

    Typical Output

    RA8007006
    

    Code

    import java.awt.*;
    import javax.swing.*;
    
    class CaptureRA {
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
                    String prefix = "RA";
                    JPanel gui = new JPanel(new FlowLayout(4));
                    gui.add(new JLabel(prefix));
                    SpinnerModel ints = new SpinnerNumberModel(
                            1000000,1000000,99999999,1);
                    JSpinner spinner = new JSpinner(ints);
                    gui.add(spinner);
    
                    JOptionPane.showMessageDialog(null, gui);
                    System.out.println(prefix + ints.getValue());
                }
            };
            // Swing GUIs should be created and updated on the EDT
            // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
            SwingUtilities.invokeLater(r);
        }
    }