Search code examples
javaswingjcomboboxjtextfield

How to restrict input types


I am learning java swing. There is an editable JComboBox for selecting different depths of water and a JTextField to accept mobile number. My question is how can I restrict the user to enter only digits in these two fields and also, how to limit the maximum number of character inputs like not more than 10 for the mobile number? Are methods available for these requirements or I need to define them of my own? Thanks in advance for your help.


Solution

  • Use a JFormattedTextField something like:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
    
            @Override
            public void run() {
                JFrame frame = new JFrame("JFormattedTextField Example");
                MaskFormatter fmt = null;
    
                // A phone number 10 digits 
                try {
                    fmt = new MaskFormatter("(###)-###-####");//brackets () are optional just there for my pref
                    fmt.setPlaceholderCharacter('*');//set place holder for the empty digits of the number
    
                } catch (java.text.ParseException e) {
                }
    
                JFormattedTextField tft1 = new JFormattedTextField(fmt);
    
                frame.add(tft1);
    
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
    

    This automatically has the properties you want it will only accept digits in a specified format Have a look at the docs too for more info: JFormattedTextField