实例11验证ip地址的有效性

/ 默认分类 / 没有评论 / 143浏览
**实例011验证ip地址的有效性**
关键是正则表达式,具体正则表达式的规则请看百度
最近不会更新了,开足马力全力学习java
package java11;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import org.omg.CORBA.PUBLIC_MEMBER;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.security.ProtectionDomain;
import java.awt.event.ActionEvent;

public class CheckIPAddress extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

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

    /**
     * Create the frame.
     * @return 
     */
    public CheckIPAddress() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 345, 155);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(null);
        setContentPane(contentPane);

        JLabel lblip = new JLabel("\u8BF7\u8F93\u5165IP\u5730\u5740\uFF1A");
        lblip.setBounds(22, 22, 94, 32);
        contentPane.add(lblip);

        textField = new JTextField();
        textField.setBounds(111, 26, 196, 26);
        contentPane.add(textField);
        textField.setColumns(10);

        JButton button = new JButton("\u9A8C\u8BC1");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dobutton(e);
            }
        });
        button.setBounds(121, 76, 93, 32);
        contentPane.add(button);

    }

    protected void dobutton(ActionEvent e) {
        String text = textField.getText();
        String info = matches(text);
        JOptionPane.showMessageDialog(null, info);
    }

    public static String matches(String text) {
        if (text != null && !text.isEmpty()) {
            String regex = "^(?:(?:2[0-4][0-9]\\.)|(?:25[0-5]\\.)|(?:1[0-9][0-9]\\.)|(?:[1-9][0-9]\\.)|(?:[0-9]\\.)){3}(?:(?:2[0-5][0-5])|(?:25[0-5])|(?:1[0-9][0-9])|(?:[1-9][0-9])|(?:[0-9]))$";
            if (text.matches(regex)) {
                return text+"\n是一个合法地址!";
            }else {
                return text+"\n不是一个合法地址!";
            }

        }
        return text+"请输入要验证的IP地址!";        
    }
}

具体实现: