Как проверить, является ли введенное Textfield мобильным номером в javaswing - PullRequest
2 голосов
/ 02 ноября 2011

Как проверить, является ли введенное Textfield мобильным номером в java swing

Ответы [ 5 ]

4 голосов
/ 02 ноября 2011

Не нужно прибегать к регулярным выражениям. Вместо этого используйте соответствующий компонент. То есть JFormattedTextField.

Пример

import java.awt.FlowLayout;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;

public final class FormattedTextFieldDemo {

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                try {
                    createAndShowGUI();
                } 
                catch (ParseException e) {
                    e.printStackTrace();
                }               
            }
        });
    }

    private static void createAndShowGUI() throws ParseException{
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.add(new JPhoneNumberFormattedTextField());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static final class JPhoneNumberFormattedTextField extends JFormattedTextField{

        private static final long serialVersionUID = 8997075146338662662L;

        public JPhoneNumberFormattedTextField() throws ParseException{
            super(new MaskFormatter("(###) ###-####"));
            setColumns(8);
        }

    }

}

enter image description here

А если вам нужно, чтобы формат соответствовал локали, измените экземпляр MaskFormatter.

2 голосов
/ 02 ноября 2011

для наиболее безопасного обхода вы должны реализовать DocumentListener

enter image description here

import java.awt.Dimension;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.text.*;

public class FormatPhone {

    private static void createAndShowUI() {
        JPanel panel = new JPanel();
        JFormattedTextField telefoonnummer = new JFormattedTextField(createFormatter("###/######"));
        Dimension teleSize = telefoonnummer.getPreferredSize();
        telefoonnummer.setPreferredSize(new Dimension(100, teleSize.height));
        JFormattedTextField telephoneNumberA = new JFormattedTextField(new JFormattedTextField.AbstractFormatter() {

            private static final int MAX_LENGTH = 9;
            private MaskFormatter smallFormat = createFormatter("##/######");
            private MaskFormatter bigFormat = createFormatter("###/######");
            private static final long serialVersionUID = 1L;

            @Override
            public Object stringToValue(String text) throws ParseException {
                String simpleText = text.replaceAll("/", "").replaceAll("\\.", "");
                if (simpleText.length() < MAX_LENGTH) {
                    return smallFormat.stringToValue(text);
                } else {
                    return bigFormat.stringToValue(text);
                }
            }

            @Override
            public String valueToString(Object value) throws ParseException {
                if (value != null) {
                    String valueText = (String) value;
                    System.out.println(valueText.length());
                }
                return smallFormat.valueToString(value);
            }
        });
        telephoneNumberA.setPreferredSize(telefoonnummer.getPreferredSize());
        JFormattedTextField telephoneNumberB = new JFormattedTextField(new JFormattedTextField.AbstractFormatter() {

            private static final int MAX_LENGTH = 9;
            private static final long serialVersionUID = 1L;

            @Override
            public Object stringToValue(String text) throws ParseException {
                return text.replaceAll("/", "");
            }

            @Override
            public String valueToString(Object value) throws ParseException {
                if (value == null) {
                    return null;
                }
                String valueText = (String) value;
                if (!valueText.matches("\\d+")) {
                    return null;
                }
                if (valueText.length() < MAX_LENGTH - 1) { // < 8
                    return null;
                }
                if (valueText.length() == MAX_LENGTH - 1) { // == 8
                    return valueText.substring(0, 2) + "/" + valueText.substring(2);
                } else if (valueText.length() >= MAX_LENGTH) { // >= 9
                    valueText = valueText.substring(0, 9);
                    return valueText.substring(0, 3) + "/" + valueText.substring(3);
                } else {
                    return null; 
                }
            }

            @Override
            protected DocumentFilter getDocumentFilter() {
                return new DocumentFilter() {

                    @Override
                    public void insertString(FilterBypass fb, int offset, String text,
                            AttributeSet attr) throws BadLocationException {
                        if (!text.matches("\\d+")) {
                            return;
                        }
                        String fbText = fb.getDocument().getText(0, fb.getDocument().getLength()).replaceAll("/", "");
                        if (fbText.length() + text.length() > MAX_LENGTH) {
                            return;
                        }
                        super.insertString(fb, offset, text, attr);
                    }

                    @Override
                    public void replace(FilterBypass fb, int offset, int length,
                            String text, AttributeSet attrs) throws BadLocationException {
                        if (!text.matches("\\d+")) {
                            return;
                        }
                        String fbText = fb.getDocument().getText(0, fb.getDocument().getLength()).replaceAll("/", "");
                        if (fbText.length() + text.length() - length > MAX_LENGTH) {
                            return;
                        }
                        super.replace(fb, offset, length, text, attrs);
                    }
                };
            }
        });
        telephoneNumberB.setPreferredSize(telefoonnummer.getPreferredSize());
        panel.add(telefoonnummer);
        panel.add(telephoneNumberA);
        panel.add(telephoneNumberB);
        JFrame frame = new JFrame("Format Phone Number");
        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    static MaskFormatter createFormatter(String format) {
        MaskFormatter formatter = null;
        try {
            formatter = new MaskFormatter(format);
            formatter.setPlaceholderCharacter('.');
        } catch (java.text.ParseException exc) {
            System.err.println("formatter is bad: " + exc.getMessage());
            System.exit(-1);
        }
        return formatter;
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowUI();
            }
        });
    }

    private FormatPhone() {
    }
}
1 голос
/ 02 ноября 2011

Сила шаблона, начинающаяся с 3 цифр, за которыми следует «-» и 7 цифр в конце.Все телефонные номера должны быть в формате «xxx-xxxxxxx».Например,

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePhoneNumber {
  public static void main(String[] argv) {

      String sPhoneNumber = "605-8889999";
      //String sPhoneNumber = "605-88899991";
      //String sPhoneNumber = "605-888999A";

      Pattern pattern = Pattern.compile("\\d{3}-\\d{7}");
      Matcher matcher = pattern.matcher(sPhoneNumber);

      if (matcher.matches()) {
          System.out.println("Phone Number Valid");
      } else {
          System.out.println("Phone Number must be in the form XXX-XXXXXXX");
      }
  }
}

\\ d = разрешена только цифра

{3} = длина

{7} = длина

0 голосов
/ 02 ноября 2011

А как же:

String number = textfield.getText();
number = number.replace(" ", ""); // Remove spaces, sometimes people seperate different
                                 // parts of the number with them
boolean valid = number.matches("[0-9]{6,10}"); // Assuming a number can have any length
                                               // from 6 to ten
0 голосов
/ 02 ноября 2011

Я бы предположил, что выполнение проверки на основе регулярных выражений при нажатии или кнопке или через DocumentListener для непрерывной проверки при изменении содержимого текстового поля решит вашу проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...