【Java例题】8.2 手工编写字符串统计的可视化程序

 


2. 手工编写字符串统计的可视化程序。 一个Frame窗体容器,布局为null,两个TextField组件,一个Button组件。 Button组件上添加ActionEvent事件监听器ActionListener和函数actionPerformed, 其中,第一个TextField组件进行输入,第二个TextField组件用于输出, 并完成输入的字符串中字母、数字、汉字及其它字符的数量统计, 统计结果显示在第二个TextField组件中。 注意:还需要对Frame窗体添加WindowEvent事件监听器WindowAdapter和 函数windowClosing,退出程序。 

 

复制代码
package chapter8;

import java.awt.Button;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class demo2 {
    public static void main(String[] args) {
        Frame f1=new Frame("字符串统计");
        f1.setLayout(null);
        int f1width=800;
        int f1height=600;
        f1.setBounds(0, 0, f1width, f1height);
        TextField tf1=new TextField();
        tf1.setBounds(50,50,f1width-100,f1height/3);
        TextField tf2=new TextField();
        tf2.setBounds(50, f1height/3+80, f1width-100, f1height/3);
        Button bt1=new Button("统计");
        bt1.setBounds(f1width/2-50, f1height/3*2+80, 100,100);
        f1.add(tf1);
        f1.add(tf2);
        f1.add(bt1);
        f1.setVisible(true);
        MyWindowAdapter mwa=new MyWindowAdapter();
        f1.addWindowListener(mwa);
        MyActionListener mal=new MyActionListener(tf1,tf2);
        bt1.addActionListener(mal);
    }
    static class MyActionListener implements ActionListener{
        TextField tf1;
        TextField tf2;
        
        MyActionListener(TextField tf1,TextField tf2){
            this.tf1=tf1;
            this.tf2=tf2;
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            String str=tf1.getText();
            int da=0;
            int xiao=0;
            int shu=0;
            int han=0;
            int els=0;
            for(int i=0;i<str.length();i++) {
                char c=str.charAt(i);
                if(c>='A'&&c<='Z') {
                    da=da+1;
                }else if(c>='a'&&c<='z'){
                    xiao=xiao+1;
                }else if(c>='0'&&c<='9') {
                    shu=shu+1;
                }else if(c>=0x4E00&&c<=0x9FA5) {
                    han=han+1;
                }else {
                    els=els+1;
                }
            }
            tf2.setText("大写:"+da+" 小写:"+xiao+" 数字:"+shu+" 汉字:"+han+" 其他"+els);
        }
    }
    static class MyWindowAdapter extends WindowAdapter{
        public void windowClosing(WindowEvent e) {
            System.exit(-1);
        }
    }
}
复制代码

 

posted @   海底淤泥  阅读(270)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示