package com.bfs.main; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class ExecutionMain extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 4757702907638719673L; // JTextField userTextTimeS ; public static void main(String args[]) { new ExecutionMain(); } ExecutionMain() { // 高度设置用 int hight = 0; // 外观风格 JFrame.setDefaultLookAndFeelDecorated(true); // 创建及设置窗口 JFrame frame = new JFrame("HelloWorldSwing"); frame.setLayout(null); frame.setSize(550, 200); // 允许用户自定义大小 frame.setResizable(false); // 窗口初始化出现在屏幕中央 frame.setLocationRelativeTo(null); // 点击x时动作为结束APP frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 添加 “开始时间” 标签 JLabel label = new JLabel("开始时间"); label.setBounds(20, hight, 65, 20); frame.add(label); // 添加 “开始时间” 输入 userTextTimeS = new JTextField(10); userTextTimeS.setBounds(85, hight + 1, 65, 20); frame.add(userTextTimeS); hight = +30; // 添加提交按钮 JButton button = new JButton("提交"); button.setBounds(10, hight, 60, 25); frame.add(button); button.addActionListener(this); // 显示窗口 frame.setVisible(true); } @Override public void actionPerformed(ActionEvent args) { // 按钮名取得 String actionCommand = args.getActionCommand(); if(actionCommand == "提交") { //获取输入的时间 String _userTextTimeS = userTextTimeS.getText(); //时间check timeCheck(_userTextTimeS); // JOptionPane.showMessageDialog(this, "时间格式不正确"); } } //时间验证 public static boolean timeCheck(String time) { //获取输入的时间并进行转换 time = time.replaceAll(":", ""); //获得时间小时部分 String Tmhh = time.substring(0, 2); //获得时间分钟部分 String Tmmm = time.substring(2, 4); //正则表达式 String sPatternTmhh = "^[0][0-9]$|^[1][0-9]$|^[2][0-3]$"; String sPatternTmmm = "^[0][0-9]$|^[1-5][0-9]$"; Boolean flgH = Pattern.matches(sPatternTmhh, Tmhh); Boolean flgM = Pattern.matches(sPatternTmmm, Tmmm); if(flgH) { System.out.println("小时正确"); }else { System.out.println("小时错误"); } if(flgM) { System.out.println("分钟正确"); }else { System.out.println("分钟错误"); } return true; } }
原文:https://www.cnblogs.com/zzh941210/p/14846198.html