【题目】java图形界面(七)---
组件综合练习
【时间】2020.05.21 周四
目录
这是how2Java网站的【图形界面】--组件综合练习 答案
主要参考评论区,可能存在bug。
链接:(七)组件综合练习
七、组件综合练习

7.1 练习-为空判断.
在JTextField中输入数据,在旁边加一个按钮JButton,当点击按钮的时候,判断JTextFiled中有没有数据,并使用JOptionPane进行提示。
1、JButton事件响应:actionPerformed(ActionEvent e)
2、JTextFiled组件内容获取
3、JOptionPane弹窗组件使用。
JOptionPane.showMessageDialog(jf,"内容");

代码:
package gui;
import javax.swing.*;
import java.awt.*;
import java.sql.*;
public class TestGUI {
public static void main(String[] args){
JFrame jf = new JFrame("LOL");
jf.setSize(416,300);
jf.setLocation(500,300);
jf.setLayout(null);
JPanel jp = new JPanel();
jp.setBounds(8,8,400,300);
jp.setLayout(new FlowLayout());
JTextField content = new JTextField("");
content.setPreferredSize(new Dimension(80,30));
JButton jb = new JButton("检测");
jb.setSize(50,30);
jb.addActionListener(e->{
String cont = content.getText();
if(cont.isEmpty()){
JOptionPane.showMessageDialog(jf,"文本内容为空");}
else{
JOptionPane.showMessageDialog(jf,"文本内容为:"+cont);
}
});
jp.add(content);
jp.add(jb);
jf.add(jp);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
7.2 练习-数字校验.
在JTextField中输入数据,在旁边加一个按钮JButton,当点击按钮的时候,判断JTextFiled中的数据是否是数字,并使用JOptionPane进行提示
判断是否为数字: https://blog.youkuaiyun.com/qq_42133100/article/details/92158507?
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}


代码:
package gui;
import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.util.regex.Pattern;
public class TestGUI {
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
public static void main(String[] args){
JFrame jf = new JFrame("LOL");
jf.setSize(416,300);
jf.setLocation(500,300);
jf.setLayout(null);
JPanel jp = new JPanel();
jp.setBounds(8,8,400,300);
jp.setLayout(new FlowLayout());
JTextField content = new JTextField("");
content.setPreferredSize(new Dimension(80,30));
JButton jb = new JButton("检测");
jb.setSize(50,30);
jb.addActionListener(e->{
String cont = content.getText();
if(cont.isEmpty()) {
JOptionPane.showMessageDialog(jf,"输入框内容为空");}
else{