1. 程式人生 > >Java 圖形化實現一個驗證電話號碼是否合法的程式

Java 圖形化實現一個驗證電話號碼是否合法的程式

package com.wxj;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class CheckPhoneNum extends JFrame{
	private JPanel contentPane;
	private JTextField nameField;
	private JTextField phoneField;
	private JTextField ageField;

	public static void main(String[] args){
		EventQueue.invokeLater(new Runnable(){
			public void run(){
				try{
					CheckPhoneNum frame = new CheckPhoneNum();
					frame.setVisible(true);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}


	public CheckPhoneNum(){
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100,100,260,190);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5,5,5,5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel label = new JLabel("姓名");
		label.setBounds(10,15,122,15);
		contentPane.add(label);

		nameField = new JTextField();
		nameField.setBounds(80,10,141,25);
		contentPane.add(nameField);


		JLabel label_1 = new JLabel("年齡");
		label_1.setBounds(10,50,122,15);
		contentPane.add(label_1);

		ageField = new JTextField();
		ageField.setBounds(80,45,141,25);
		contentPane.add(ageField);

		JLabel label_2 = new JLabel("電話號碼");
		label_2.setBounds(10,87,122,15);
		contentPane.add(label_2);

		phoneField = new JTextField();
		phoneField.setBounds(80,82,141,25);
		contentPane.add(phoneField);

		JButton button = new JButton("驗證");
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				do_button_actionPerformed(e);
			}
		});
		button.setBounds(100,120,60,25);
		contentPane.add(button);
	}

	protected void do_button_actionPerformed(ActionEvent e){
		String text = phoneField.getText();
		String info = check(text);  //對輸入的電話文字進行驗證
		JOptionPane.showMessageDialog(null,info);
	}

	public String check(String text){
		if(text == null || text.isEmpty()){
			return "請輸入電話號碼";
		}
		String regex = "^\\d{3}-?\\d{8}|\\d{4}-?\\d{8}|\\d{4}-?\\d{7}$";  //正則表示式
		if(text.matches(regex)){
			return text + "\n是一個合法的電話號碼";
		}else{
			return text + "\n不是一個合法的電話號碼";
		}
	}
}