java 学习案列
目录
java 案列集锦
package com.swtdesigner;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.ImageIcon;
/**
* Utility class for managing resources such as colors, fonts, images, etc.
*
* This class may be freely distributed as part of any application or plugin.
* <p>
* Copyright (c) 2003 - 2004, Instantiations, Inc. <br>All Rights Reserved
*
* @author scheglov_ke
*/
public class SwingResourceManager {
/**
* Maps image names to images
*/
private static HashMap<String, Image> m_ClassImageMap = new HashMap<String, Image>();
/**
* Returns an image encoded by the specified input stream
* @param is InputStream The input stream encoding the image data
* @return Image The image encoded by the specified input stream
*/
private static Image getImage(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buf[] = new byte[1024 * 4];
while (true) {
int n = is.read(buf);
if (n == -1)
break;
baos.write(buf, 0, n);
}
baos.close();
return Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
} catch (Throwable e) {
return null;
}
}
/**
* Returns an image stored in the file at the specified path relative to the specified class
* @param clazz Class The class relative to which to find the image
* @param path String The path to the image file
* @return Image The image stored in the file at the specified path
*/
public static Image getImage(Class<?> clazz, String path) {
String key = clazz.getName() + '|' + path;
Image image = m_ClassImageMap.get(key);
if (image == null) {
if ((path.length() > 0) && (path.charAt(0) == '/')) {
String newPath = path.substring(1, path.length());
image = getImage(new BufferedInputStream(clazz.getClassLoader().getResourceAsStream(newPath)));
} else {
image = getImage(clazz.getResourceAsStream(path));
}
m_ClassImageMap.put(key, image);
}
return image;
}
/**
* Returns an image stored in the file at the specified path
* @param path String The path to the image file
* @return Image The image stored in the file at the specified path
*/
public static Image getImage(String path) {
return getImage("default", path); //$NON-NLS-1$
}
/**
* Returns an image stored in the file at the specified path
* @param section String The storage section in the cache
* @param path String The path to the image file
* @return Image The image stored in the file at the specified path
*/
public static Image getImage(String section, String path) {
String key = section + '|' + SwingResourceManager.class.getName() + '|' + path;
Image image = m_ClassImageMap.get(key);
if (image == null) {
try {
FileInputStream fis = new FileInputStream(path);
image = getImage(fis);
m_ClassImageMap.put(key, image);
fis.close();
} catch (IOException e) {
return null;
}
}
return image;
}
/**
* Clear cached images in specified section
* @param section the section do clear
*/
public static void clearImages(String section) {
for (Iterator<String> I = m_ClassImageMap.keySet().iterator(); I.hasNext();) {
String key = I.next();
if (!key.startsWith(section + '|'))
continue;
Image image = m_ClassImageMap.get(key);
image.flush();
I.remove();
}
}
/**
* Returns an icon stored in the file at the specified path relative to the specified class
* @param clazz Class The class relative to which to find the icon
* @param path String The path to the icon file
* @return Icon The icon stored in the file at the specified path
*/
public static ImageIcon getIcon(Class<?> clazz, String path) {
return getIcon(getImage(clazz, path));
}
/**
* Returns an icon stored in the file at the specified path
* @param path String The path to the icon file
* @return Icon The icon stored in the file at the specified path
*/
public static ImageIcon getIcon(String path) {
return getIcon("default", path); //$NON-NLS-1$
}
/**
* Returns an icon stored in the file at the specified path
* @param section String The storage section in the cache
* @param path String The path to the icon file
* @return Icon The icon stored in the file at the specified path
*/
public static ImageIcon getIcon(String section, String path) {
return getIcon(getImage(section, path));
}
/**
* Returns an icon based on the specified image
* @param image Image The original image
* @return Icon The icon based on the image
*/
public static ImageIcon getIcon(Image image) {
if (image == null)
return null;
return new ImageIcon(image);
}
}
package com.wgh;
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.JTextField;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;
import com.wgh.IntJTextField;
public class MainFrame extends JFrame {
private JTextField new3;
private JTextField new2;
private JTextField new1;
/**
* Launch the application
*
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public MainFrame() {
super();
setTitle("输入3个数按从小到大的顺序输出");
getContentPane().setLayout(null);
setBounds(100, 100, 444, 141);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final BackgroundPanel backgroundPanel = new BackgroundPanel();
backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class,
"/images/background.jpg"));
backgroundPanel.setBounds(0, 0, 436, 107);
getContentPane().add(backgroundPanel);
final JLabel label = new JLabel();
label.setText("请输入3个整数:");
label.setBounds(15, 30, 98, 18);
backgroundPanel.add(label);
final IntJTextField intJTextField1 = new IntJTextField();
intJTextField1.setBounds(122, 30, 72, 22);
backgroundPanel.add(intJTextField1);
final IntJTextField intJTextField2 = new IntJTextField();
intJTextField2.setBounds(200, 30, 72, 22);
backgroundPanel.add(intJTextField2);
final IntJTextField intJTextField3 = new IntJTextField();
intJTextField3.setBounds(278, 30, 72, 22);
backgroundPanel.add(intJTextField3);
final JLabel label_1 = new JLabel();
label_1.setText("排序后输出:");
label_1.setBounds(35, 65, 84, 18);
backgroundPanel.add(label_1);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent arg0) {
int number1 = intJTextField1.getInt(); // 获取第1个数
int number2 = intJTextField2.getInt(); // 获取第2个数
int number3 = intJTextField3.getInt(); // 获取第3个数
int temp = 0; // 临时变量
if (number1 > number2) { // 对于第1个数和第2个数按从小到大排序
temp = number1; // 保存第1个数到临时变量中
number1 = number2; // 将第2个数赋给第1个数
number2 = temp; // 将临时变量中的数赋给第2个数
}
if (number1 > number3) { // 对于第1个数和第3个数按从小到大排序
temp = number1; // 保存第1个数到临时变量中
number1 = number3;// 将第3个数赋给第1个数
number3 = temp; // 将临时变量中的数赋给第3个数
}
if (number2 > number3) { // 对于第2个数和第3个数按从小到大排序
temp = number2; // 保存第2个数到临时变量中
number2 = number3;// 将第3个数赋给第2个数
number3 = temp; // 将临时变量中的数赋给第3个数
}
new1.setText(String.valueOf(number1));
new2.setText(String.valueOf(number2));
new3.setText(String.valueOf(number3));
}
});
button.setText("排序");
button.setBounds(360, 45, 60, 28);
backgroundPanel.add(button);
new1 = new JTextField();
new1.setFocusable(false);
new1.setBounds(123, 61, 72, 22);
backgroundPanel.add(new1);
new2 = new JTextField();
new2.setFocusable(false);
new2.setBounds(200, 60, 72, 22);
backgroundPanel.add(new2);
new3 = new JTextField();
new3.setFocusable(false);
new3.setBounds(280, 60, 72, 22);
backgroundPanel.add(new3);
//
}
}
在窗体显示九九乘法表
package com.wgh;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;
public class MainFrame extends JFrame {
private JTextArea showTextArea;
/**
* Launch the application
*
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public MainFrame() {
super();
getContentPane().setLayout(null);
setTitle("在窗体上输出九九乘法表");
setBounds(100, 100, 554, 372);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//**********实现输出九九乘法表的代码*********************************/
String str = new String(); // 定义一个空的字符串
for (int i = 1; i <= 9; i++) { // 第一层循环
for (int j = 1; j <= i; j++) { // 第二次循环
str += j + "×" + i + "=" + j * i; // 连接乘法表中的一个等式
str += "\t"; // 在每个等式后面添加一个Tab符
}
str += "\r\n"; // 在当前字符串的结果处添加回车换行符
}
//*****************************************************************/
final BackgroundPanel backgroundPanel = new BackgroundPanel();
backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/images/background.jpg"));
backgroundPanel.setBounds(0, 0, 546, 340);
getContentPane().add(backgroundPanel);
showTextArea = new JTextArea();
showTextArea.setBounds(25, 135, 491, 177);
backgroundPanel.add(showTextArea);
showTextArea.setOpaque(false);
showTextArea.setBackground(new Color(250, 250, 210));
showTextArea.setForeground(Color.BLACK);
showTextArea.setFocusable(false);
showTextArea.setBorder(new LineBorder(new Color(30, 144, 255), 0, false));
showTextArea.setTabSize(5);
showTextArea.setText(str); // 将生成的九九乘法表的字符串显示到文本域中
}
}
黄蓉难倒瑛姑的题目
package com.wgh;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Toolkit;
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.JTextArea;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;
public class MainFrame extends JFrame {
private JTextArea answer;
private JTextArea question;
/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public MainFrame() {
super();
setTitle("解决黄蓉难倒瑛姑的数学题");
getContentPane().setLayout(null);
setBounds(100, 100, 566, 607);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final BackgroundPanel backgroundPanel = new BackgroundPanel();
backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/images/background3.JPG"));
backgroundPanel.setBounds(0, 0, 558, 573);
getContentPane().add(backgroundPanel);
question = new JTextArea();
question.setOpaque(false);
question.setFocusable(false);
question.setLineWrap(true);
question.setText("今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问几何?");
question.setBounds(285, 49, 147, 69);
backgroundPanel.add(question);
final JButton button = new JButton();
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button.setContentAreaFilled(false);
button.setOpaque(false);
button.setBorderPainted(false);
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent arg0) {
String number=new String(); //定义一个空的字符串
for (int j = 1; j < 1000; j++) {
if (j % 3 == 2 && j % 5 == 3 && j % 7 == 2) {
System.out.println(j);
number+=String.valueOf(j)+" ";
}
}
answer.setText(number);
}
});
button.setBounds(342, 357, 34, 58);
backgroundPanel.add(button);
answer = new JTextArea();
answer.setOpaque(false);
answer.setTabSize(4);
answer.setBackground(Color.WHITE);
answer.setLineWrap(true);
answer.setFocusable(false);
answer.setBounds(158, 285, 117, 58);
backgroundPanel.add(answer);
//
}
}
switch 判断生肖年份
package com.wgh;
import java.awt.BorderLayout;
import java.awt.Color;
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.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;
import com.wgh.IntJTextField;
public class MainFrame extends JFrame {
/**
* Launch the application
*
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public MainFrame() {
super();
getContentPane().setLayout(null);
setTitle("应用switch语句实现生肖查询");
setBounds(100, 100, 421, 254);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final BackgroundPanel backgroundPanel = new BackgroundPanel();
backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class,
"/images/background.jpg"));
backgroundPanel.setBounds(0, 0, 413, 220);
getContentPane().add(backgroundPanel);
final JLabel label = new JLabel();
label.setText("请输入出生年份:");
label.setBounds(75, 125, 104, 18);
backgroundPanel.add(label);
final IntJTextField yearText = new IntJTextField();
yearText.setBorder(new EmptyBorder(0, 0, 0, 0));
yearText.setBackground(new Color(226, 243, 250));
yearText.setBounds(180, 123, 100, 22);
backgroundPanel.add(yearText);
final JLabel result = new JLabel();
result.setBounds(40, 175, 314, 18);
backgroundPanel.add(result);
final JButton button = new JButton();
button.setPressedIcon(SwingResourceManager.getIcon(MainFrame.class, "/images/buttonbg.png"));
button.setRolloverIcon(SwingResourceManager.getIcon(MainFrame.class, "/images/buttonbg1.png"));
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setIcon(SwingResourceManager.getIcon(MainFrame.class, "/images/buttonbg.png"));
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
int year = yearText.getInt(); // 获取输入的年份
if (year < 1 || year > 9999) { // 判断输入的年份是否正确
result.setText("您输入的年份不正确!");
} else {
// 通过switch语句判断生肖
switch (year % 12) { // 年份与12求余
case 4: // 余数为4
result.setText("您的生肖为:鼠");
break;
case 5: // 余数为5
result.setText("您的生肖为:牛");
break;
case 6: // 余数为6
result.setText("您的生肖为:虎");
break;
case 7: // 余数为7
result.setText("您的生肖为:兔");
break;
case 8: // 余数为8
result.setText("您的生肖为:龙");
break;
case 9: // 余数为9
result.setText("您的生肖为:蛇");
break;
case 10: // 余数为10
result.setText("您的生肖为:马");
break;
case 11: // 余数为11
result.setText("您的生肖为:羊");
break;
case 0: // 余数为0
result.setText("您的生肖为:猴");
break;
case 1: // 余数为1
result.setText("您的生肖为:鸡");
break;
case 2: // 余数为2
result.setText("您的生肖为:狗");
break;
case 3: // 余数为3
result.setText("您的生肖为:猪");
}
}
}
});
button.setBounds(286, 125, 79, 19);
backgroundPanel.add(button);
//
}
}
分割字符串
package com.ityang.java;
public class Division { //创建类
public static void main(String args[]) { //主方法
String str = new String("abc,def,ghi,gkl"); //定义的字符串str
String[] newstr = str.split(","); //使用split()方法对字符串进行拆分,返回字符串数组
for (int i = 0; i < newstr.length; i++) { //使用for循环遍历字符数组
System.out.println(newstr[i]); //输出信息
}
String[] newstr2 = str.split(",",2); //对字符串进行拆分,并限定拆分次数,返回字符数组
for(int j = 0;j<newstr2.length;j++){ //循环遍历字符数组
System.out.println(newstr2[j]); //输出信息
}
}
}
日期格式化
Date date = new Date(); //创建Date对象
dateString s = String.format("%te", date); //通过format()方法对date进行格式化上述代码变量s的值是当前日期中的天数,
如今天是15号,则s的值为15。“%te”是转换符,常用的日期和时间的格式转换符如表1所示。
时间格式化
package com.ityang.java;
import java.util.Date;
public class GetDate {
public static void main(String[] args) {
Date date = new Date();
System.out.println("2位数字的24时制的小时(00-23)现在是:" + String.format("%tH", date) + "点");
System.out.println("2位数字的12时制的小时(01-12)现在是:" + String.format("%tI", date) + "点");
System.out.println("2位数字的24时制的小时(0-23)现在是:" + String.format("%tk", date) + "点");
System.out.println("2位数字的12时制的小时(1-12)现在是:" + String.format("%tl", date) + "点");
System.out.println("现在是:" + String.format("%tH", date) + "时" + String.format("%tM", date) + "分"
+ String.format("%tS", date) + "秒");
}
}
格式化常见的日期时间组合
常规类型格式化
正则表达式
public class Judge { //新建类
public static void main(String[] args) { //主方法
String regex = "\\w{0,}\\@\\w{0,}\\.{1}\\w{0,}"; //正则表达式,定义邮箱格式
String str1 = "aaa@"; //定义字符串str1
String str2 = "aaaa"; //定义字符串str2
String str3 = "aaaaa@111.com"; //定义字符串str3
if(str1.matches(regex)){ //matches()方法可判断字符串是否与正则表达式匹配
System.out.println(str1+" 是一个E_mail地址格式"); //输出信息
}
if(str2.matches(regex)){ //判断字符串str2是否与正则表达式匹配
System.out.println(str2+" 是一个E_mail地址格式"); //输出信息
}
if(str3.matches(regex)){ //判断字符串str3是否与正则表达式匹配
System.out.println(str3+" 是一个E_mail地址格式"); //输出信息
}
else{ //如果str1、str2、str3与正则表达式都不匹配
System.out.println("都不是E_mail地址格式"); //输出信息
}
}
}
java 正则表达式的语法案列
匹配验证-验证Email是否正确
public static void main(String[] args) {
// 要验证的字符串
String str = "service@xsoftlab.net";
// 邮箱验证规则
String regEx = "[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 字符串是否与正则表达式相匹配
boolean rs = matcher.matches();
System.out.println(rs);
}
在字符串中查询字符或者字符串
public static void main(String[] args) {
// 要验证的字符串
String str = "baike.xsoftlab.net";
// 正则表达式规则
String regEx = "baike.*";
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 查找字符串中是否有匹配正则表达式的字符/字符串
boolean rs = matcher.find();
System.out.println(rs);
}
正则表达式验证IP地址
package com.ityang.java;
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 CheckIPAddress extends JFrame {
private JPanel contentPane;
private JTextField ipField;
/**
* 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.
*/
public CheckIPAddress() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 280, 128);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblip = new JLabel("\u8BF7\u8F93\u5165IP\u5730\u5740\uFF1A");
lblip.setBounds(12, 14, 92, 15);
contentPane.add(lblip);
ipField = new JTextField();
ipField.setBounds(100, 10, 141, 25);
contentPane.add(ipField);
JButton button = new JButton("\u9A8C\u8BC1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setBounds(66, 57, 93, 23);
contentPane.add(button);
}
protected void do_button_actionPerformed(ActionEvent e) {
String text = ipField.getText();// 获取用户输入
String info = ipCheck(text);// 对输入文本进行IP验证
JOptionPane.showMessageDialog(null, info);// 用对话框输出验证结果
}
/**
* 验证ip是否合法
*
* @param text
* ip地址
* @return 验证信息
*/
public String ipCheck(String text) {
if (text != null && !text.isEmpty()) {
// 定义正则表达式
String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
// 判断ip地址是否与正则表达式匹配
if (text.matches(regex)) {
// 返回判断信息
return text + "\n是一个合法的IP地址!";
} else {
// 返回判断信息
return text + "\n不是一个合法的IP地址!";
}
}
// 返回判断信息
return "请输入要验证的IP地址!";
}
}
正则表达式鉴别非法电话号码
package com.ityang.java;
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 phoneNumField;
private JTextField ageField;
/**
* Launch the application.
*/
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();
}
}
});
}
/**
* Create the frame.
*/
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 lblip = new JLabel("\u59D3\u540D\uFF1A");
lblip.setBounds(10, 15, 122, 15);
contentPane.add(lblip);
nameField = new JTextField();
nameField.setBounds(80, 10, 141, 25);
contentPane.add(nameField);
JButton button = new JButton("\u9A8C\u8BC1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setBounds(90, 119, 93, 23);
contentPane.add(button);
JLabel label = new JLabel("\u7535\u8BDD\u53F7\u7801\uFF1A");
label.setBounds(10, 87, 60, 15);
contentPane.add(label);
phoneNumField = new JTextField();
phoneNumField.setBounds(80, 82, 141, 25);
contentPane.add(phoneNumField);
JLabel label_1 = new JLabel("\u5E74\u9F84\uFF1A");
label_1.setBounds(10, 50, 122, 15);
contentPane.add(label_1);
ageField = new JTextField();
ageField.setBounds(80, 45, 141, 25);
contentPane.add(ageField);
}
protected void do_button_actionPerformed(ActionEvent e) {
String text = phoneNumField.getText();// 获取用户输入
String info = check(text);// 对输入文本进行IP验证
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}$";
// 判断输入数据是否为电话号码
if (text.matches(regex)) {
return text + "\n是一个合法的电话号码!";
} else {
return text + "\n不是一个合法的电话号码!";
}
}
}
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 CheckEmail extends JFrame {
private JPanel contentPane;
private JTextField phoneNumField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CheckEmail frame = new CheckEmail();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CheckEmail() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 260, 122);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton button = new JButton("\u9A8C\u8BC1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setBounds(90, 47, 93, 23);
contentPane.add(button);
JLabel lblEmail = new JLabel("Email\u5730\u5740\uFF1A");
lblEmail.setBounds(10, 15, 70, 15);
contentPane.add(lblEmail);
phoneNumField = new JTextField();
phoneNumField.setBounds(90, 10, 141, 25);
contentPane.add(phoneNumField);
}
protected void do_button_actionPerformed(ActionEvent e) {
String text = phoneNumField.getText();// 获取用户输入
String info = check(text);// 对输入文本进行IP验证
JOptionPane.showMessageDialog(null, info);// 用对话框输出验证结果
}
public String check(String text) {
if (text == null || text.isEmpty()) {
return "请输入Email!";
}
// 定义正则表达式
String regex = "\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
// 判断输入数据是否为Email地址
if (text.matches(regex)) {
return text + "\n是一个合法的Email!";
} else {
return text + "\n不是一个合法的Email!";
}
}
}
获取字符串中汉字的个数
import java.awt.EventQueue;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class ChineseAmount extends JFrame {
private JPanel contentPane;
private JTextArea chineseArea;
private JTextField numField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ChineseAmount frame = new ChineseAmount();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ChineseAmount() {
setTitle("\u83B7\u53D6\u6C49\u5B57\u6570\u91CF");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 193);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("\u8F93\u5165\u4E00\u6BB5\u6587\u5B57\uFF1A");
label.setBounds(12, 14, 101, 15);
contentPane.add(label);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(109, 14, 313, 99);
contentPane.add(scrollPane);
chineseArea = new JTextArea();
chineseArea.setLineWrap(true);
scrollPane.setViewportView(chineseArea);
JButton button = new JButton("\u8BA1\u7B97");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setBounds(109, 116, 101, 25);
contentPane.add(button);
numField = new JTextField();
numField.setBounds(222, 118, 63, 21);
contentPane.add(numField);
numField.setColumns(10);
JLabel label_1 = new JLabel("\u4E2A\u6C49\u5B57");
label_1.setBounds(297, 121, 54, 15);
contentPane.add(label_1);
}
protected void do_button_actionPerformed(ActionEvent e) {
String text = chineseArea.getText();// 获取用户输入
int amount = 0;// 创建汉字数量计数器
for (int i = 0; i < text.length(); i++) {// 遍历字符串每一个字符
// 使用正则表达式判断字符是否属于汉字编码
boolean matches = Pattern.matches("^[\u4E00-\u9FA5]{0,}$", ""
+ text.charAt(i));
if (matches) {// 如果是汉字
amount++;// 累加计数器
}
}
numField.setText(amount + "");// 在文本框显示汉字数量。
}
}
import java.awt.EventQueue;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class CharCount extends JFrame {
private JPanel contentPane;
private JTextArea chineseArea;
private JTextField numField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CharCount frame = new CharCount();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CharCount() {
setTitle("\u83B7\u53D6\u6C49\u5B57\u6570\u91CF");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 193);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("\u8F93\u5165\u4E00\u6BB5\u6587\u5B57\uFF1A");
label.setBounds(12, 14, 101, 15);
contentPane.add(label);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(109, 14, 313, 99);
contentPane.add(scrollPane);
chineseArea = new JTextArea();
chineseArea.setLineWrap(true);
scrollPane.setViewportView(chineseArea);
JButton button = new JButton("\u8BA1\u7B97");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
do_button_actionPerformed(e);
}
});
button.setBounds(109, 116, 101, 25);
contentPane.add(button);
numField = new JTextField();
numField.setBounds(222, 118, 63, 21);
contentPane.add(numField);
numField.setColumns(10);
JLabel label_1 = new JLabel("\u4E2A\u6C49\u5B57");
label_1.setBounds(297, 121, 54, 15);
contentPane.add(label_1);
}
protected void do_button_actionPerformed(ActionEvent e) {
String text = chineseArea.getText();// 获取用户输入
int amount = 0;// 创建汉字数量计数器
for (int i = 0; i < text.length(); i++) {// 遍历字符串每一个字符
// 使用正则表达式判断字符是否属于汉字编码
boolean matches = Pattern.matches("^[\u4E00-\u9FA5]{0,}$", ""
+ text.charAt(i));
if (!matches) {// 如果是汉字
amount++;// 累加计数器
}
}
numField.setText(amount + "");// 在文本框显示汉字数量。
}
}