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

柔情痞子 提交于 2019-12-20 04:57:07

问题


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.


回答1:


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

Image

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);
    }
}


来源:https://stackoverflow.com/questions/16270983/validate-jtextfield-value-so-that-it-starts-with-ra-then-has-8-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!