当前位置:

首页 > 编程开发 > 怎么利用Java实现带GUI的气泡诗词特效

怎么利用Java实现带GUI的气泡诗词特效

实现效果实现第个气泡中心显示一个字,在框中随意运动,用空格键按下运行停止,再按下左键运动继续。用鼠标左键按下选中的圆变为填充的,再次按下又变为不填充的。示例代码AlgoVisualizer.javaimportjava.awt.*;importjava.awt.event.*;publicclassAlgoVisualizer{privateObjectdata;privateCircle[]circles;privateAlgoFrameframe;privatebooleanisAnmiated=tr

本文目录

    实现效果

    怎么利用Java实现带GUI的气泡诗词特效

    实现第个气泡中心显示一个字,在框中随意运动,用空格键按下运行停止,再按下左键运动继续。用鼠标左键按下选中的圆变为填充的,再次按下又变为不填充的。

    示例代码

    AlgoVisualizer.java

    import java.awt.*;
    import java.awt.event.*;
     
    public class AlgoVisualizer {
        private Object data;
        private Circle[] circles;
        private AlgoFrame frame;
        private boolean isAnmiated = true;
     
        public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){
     
            circles = new Circle[N];
            int R = 50;
     
            for(int i = 0; i < N; i++)
            {
                int x = (int)(Math.random()*(sceneWidth-2*R)) + R;
                int y = (int)(Math.random()*(sceneHeight-2*R)) + R;
     
                int vx = (int)(Math.random()*11) - 5;
                int vy = (int)(Math.random()*11) - 5;
                circles[i] = new Circle(x, y, R, vx, vy);
     
            }
     
            EventQueue.invokeLater(()->{
                 frame = new AlgoFrame("Welcome-Java", sceneWidth, sceneHeight);
                 frame.addKeyListener(new AlgoKeyListener());
                frame.addMouseListener(new AlgoMouseListener());
     
                new Thread(()->{run();}).start();
            });
        }
     
     
        public AlgoVisualizer(int sceneWidth, int sceneHeight, int N, String centerLael){
     
            Circle.showLabel = true;
     
            circles = new Circle[N];
            int R = 50;
     
            for(int i = 0; i < N; i++)
            {
                int x = (int)(Math.random()*(sceneWidth-2*R)) + R;
                int y = (int)(Math.random()*(sceneHeight-2*R)) + R;
     
                int vx = (int)(Math.random()*11) - 5;
                int vy = (int)(Math.random()*11) - 5;
                circles[i] = new Circle(x, y, R, vx, vy);
                circles[i] = new Circle(x, y, R, vx, vy, centerLael.charAt(i) + "");
     
            }
     
            EventQueue.invokeLater(()->{
                frame = new AlgoFrame("Welcome-Java", sceneWidth, sceneHeight);
                frame.addKeyListener(new AlgoKeyListener());
                frame.addMouseListener(new AlgoMouseListener());
                new Thread(()->{
                    run();
                }).start();
            });
        }
     
        private void run(){
     
            while(true)
            {
                //绘制当前数据
                frame.render(circles);
                AlgoVisHelper.pause(20);
                //更新数据
                if(isAnmiated)
                {
                    for(Circle circle:circles)
                        circle.move(0, 0, frame.getCanvasWidth(), frame.getCanvasHeight());
                }
            }
        }
     
        private class AlgoKeyListener extends KeyAdapter {
            @Override
            public void keyReleased(KeyEvent event)
            {
                if(event.getKeyChar() == ' ')
                {
                    isAnmiated = !isAnmiated;
                }
            }
        }
     
        private class AlgoMouseListener extends MouseAdapter{
            @Override
            public void mousePressed (MouseEvent event)
            {
                event.translatePoint(0,
    //                    (frame.getBounds().height -frame.getCanvasHeight()));
                        -(frame.getBounds().height -frame.getCanvasHeight()));
     
    //            System.out.println(event.getPoint());
     
                for(Circle circle:circles)
                {
                    if(circle.contain(event.getPoint())){
                        circle.isFilled = !circle.isFilled;
                    }
     
                }
     
            }
        }
     
        public static void main(String[] args) {
     
            String poemData = "三月七日沙湖道中遇雨。雨具先去,同行皆狼狈,余独不觉。已而遂晴,故作此词 \n" +
                    "莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马,谁怕? 一蓑烟雨任平生。\n" +
                    "料峭春风吹酒醒,微冷,山头斜照却相迎。回首向来萧瑟处,归去,也无风雨也无晴。";
     
            int sceneWidth = 800;
            int sceneHeight = 800;
            int N = 15;
     
    //        AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth, sceneHeight, N);
            AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth, sceneHeight, N, poemData);
     
        }
    }

    AlgoFrame.java

    import javax.swing.*;
    import java.awt.*;
     
     
    public class AlgoFrame extends JFrame {
        private int canvasWidth;
        private int canvasHeight;
        public AlgoFrame(String title, int canvasWidth, int canvasHeight){
     
            super(title);
     
            this.canvasHeight = canvasHeight;
            this.canvasWidth = canvasWidth;
     
     
            AlgoCanvas canvas = new AlgoCanvas();
            setContentPane(canvas);
            pack();
     
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        }
     
        public AlgoFrame(String title){
            this(title, 1024, 768);
        }
     
     
        public int getCanvasWidth(){return  canvasWidth;}
        public int getCanvasHeight() {return canvasHeight;}
     
        private Circle[] circles;
     
        public void render(Circle[] circles)
        {
            this.circles = circles;
            repaint();
        }
     
        private Object data;
        public void render(Object data)
        {
            this.data = data;
            repaint();
        }
        private class AlgoCanvas extends JPanel{
     
            public AlgoCanvas(){
                super(true);
            }
     
            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                Graphics2D g2d =(Graphics2D)g;
     
                RenderingHints hints = new RenderingHints(
                        RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.addRenderingHints(hints);
     
                AlgoVisHelper.setStrokeWidth(g2d, 1);
                AlgoVisHelper.setColor(g2d, Color.RED);
     
                g2d.setFont( new Font("SimSun", Font.BOLD, 16));
     
                for (Circle circle: circles)
                {
                    if(!circle.isFilled)
                    {
                        AlgoVisHelper.strokeCircle(g2d, circle.x, circle.y, circle.getR() );
                    }
                    else
                    {
                        AlgoVisHelper.fillCircle(g2d, circle.x, circle.y, circle.getR());
                    }
     
                    if(Circle.showLabel)
                    {
    //                    AlgoVisHelper.showPoem(g2d,circle.x, circle.y, circle.centerLabel);
                        AlgoVisHelper.drawText(g2d,circle.centerLabel,circle.x, circle.y);
     
                    }
                }
     
            }
     
            @Override
            public Dimension getPreferredSize(){
    //            System.out.println("Run getPreferredSize()");
                return new Dimension(canvasWidth, canvasHeight);
            }
        }
    }

    Circle.java

    import java.awt.*;
     
    public class Circle {
        public int x, y;
        private int r;
        public int vx, vy;
        public String centerLabel;
        static public boolean showLabel = false;
        public boolean isFilled = false;
     
        public Circle(int x, int y, int r, int vx, int vy)
        {
            this.x = x;
            this.y = y;
            this.r = r;
            this.vx = vx;
            this.vy = vy;
        }
        public Circle(int x, int y, int r, int vx, int vy, String centerLabel)
        {
            this.x = x;
            this.y = y;
            this.r = r;
            this.vx = vx;
            this.vy = vy;
            this.centerLabel = centerLabel;
        }
        public int getR(){return r;}
     
        public void move(int minx, int miny, int maxx, int maxy){
            x += vx;
            y += vy;
     
            checkCollision(minx, miny, maxx, maxy);
        }
     
        private void checkCollision(int minx, int miny, int maxx, int maxy) {
            if (x - r < minx) {
                x = r;
                vx = -vx;
            }
            if (x + r >= maxx) {
                x = maxx - r;
                vx = -vx;
            }
            if (y - r < miny) {
                y = r;
                vy = -vy;
            }
            if (y + r >= maxy) {
                y = maxy - r;
                vy = -vy;
            }
     
        }
     
        public boolean contain(Point p)
        {
            return (x - p.x) * (x - p.x) + (y - p.y)*(y - p.y) <= r*r;
        }
     
    }

    AlgoVisHelper.java

    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Rectangle2D;
     
    public class AlgoVisHelper {
        private AlgoVisHelper(){}
     
        public static void setStrokeWidth(Graphics2D g2d, int w){
            int strokeWidth = w;
            g2d.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        }
     
        public static void strokeCircle(Graphics2D g2d, int x, int y, int r){
            Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
            g2d.draw(circle);
        }
     
        public static void fillCircle(Graphics2D g2d, int x, int y, int r){
            Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
            g2d.fill(circle);
        }
     
        public static void strokeRectangle(Graphics2D g2d, int x, int y, int w, int h)
        {
            Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
            g2d.draw(rectangle);
        }
     
        public static void fillRectangle(Graphics2D g2d, int x, int y, int w, int h)
        {
            Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
            g2d.fill(rectangle);
        }
     
        public static void putImage(Graphics2D g2d, int x, int y, String imageURL){
            ImageIcon icon = new ImageIcon(imageURL);
            Image image = icon.getImage();
            g2d.drawImage(image, x, y, null);
        }
     
        public  static void drawText(Graphics2D g2d, String text, int centerx, int centery)
        {
            if(text == null)
                throw new IllegalArgumentException("Text is null");
     
            FontMetrics metrics = g2d.getFontMetrics();
            int w = metrics.stringWidth(text);
            int h = metrics.getDescent();
            g2d.drawString(text, centerx - w/2, centery + h);
        }
     
     
        public static void showPoem(Graphics2D g2d,  int x, int y, String poem){
     
            g2d.drawString(poem,x, y);
     
    //        g2d.drawString("醉", x, y);
        }
        public static void setColor(Graphics2D g2d, Color color){
            g2d.setColor(color);
        }
     
        public static void pause(int t)
        {
            try{
                Thread.sleep(t);
            }
            catch (InterruptedException e){
                System.out.println("Error in sleepping");
            }
        }
     
    }
    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Java
    相关文章 更多
    Java单元测试入门:使用JUnit 5编写第一个测试用例
    Java单元测试入门:使用JUnit 5编写第一个测试用例

    面向初学者的JUnit 5实用入门指南。从测试概念、Maven依赖配置,到手把手编写首个单元测试用例及断言验证,助你掌握Java单元测试的核心流程。

    Java变量未初始化报错解析:局部变量与成员变量默认值差异
    Java变量未初始化报错解析:局部变量与成员变量默认值差异

    深入解析Java中局部变量未初始化编译报错与成员变量自动赋予默认值的机制差异,涵盖JVM内存分配、编译期确定性赋值检查与实际排查修复方案。

    Java获取当前时间并格式化输出:DateTimeFormatter与SimpleDateFormat
    Java获取当前时间并格式化输出:DateTimeFormatter与SimpleDateFormat

    详细讲解在Java中获取当前系统时间并进行格式化输出的两种核心方案:基于Java 8全新日期时间API的DateTimeFormatter与传统遗留的SimpleDateFormat,包含完整代码示例、线程安全机制对比及生产选型建议。

    Java中final与static final常量的定义及初始化规则
    Java中final与static final常量的定义及初始化规则

    深入解析Java中final变量与static final常量的定义、内存语义、初始化时机及合法赋值路径,涵盖编译期常量优化与实战避坑指南。

    Java抽象方法与接口方法的区别及选型建议
    Java抽象方法与接口方法的区别及选型建议

    深入对比Java中抽象类抽象方法与接口方法的语法演进、设计意图及运行期差异,并提供清晰的架构选型决策流程与实战范例。

    Java实现HTTP请求与JSON解析的完整代码示例
    Java实现HTTP请求与JSON解析的完整代码示例

    本文提供Java标准库HttpClient发起HTTP GET/POST请求并结合Jackson进行JSON数据反序列化与序列化的完整代码示例与工程实践指南。

    Java递归出现StackOverflowError的原因分析及栈空间优化方案
    Java递归出现StackOverflowError的原因分析及栈空间优化方案

    详细分析Java递归调用出现StackOverflowError的原因,结合代码说明线程栈、栈帧和递归深度之间的关系,并介绍终止条件排查、迭代改写、减少栈帧开销以及通过-Xss调整JVM栈空间的方法。

    Java空指针异常(NPE)的代码排查与修复实例
    Java空指针异常(NPE)的代码排查与修复实例

    针对Java中常见的NullPointerException(NPE),本文从堆栈日志定位、典型代码触发场景、具体修复代码对比到防御体系进行系统讲解,提供实用且易上手的排查与修复方案。

    selenium上传文件教程本地文件路径设置方法
    selenium上传文件教程本地文件路径设置方法

    深入解析Selenium处理文件上传的技术细节,涵盖标准HTML控件的路径直接注入法与非标准控件的系统级模拟方案,提供Windows与Linux环境下的路径设置最佳实践及常见异常排查。

    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景
    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景

    针对大数据工程场景,系统对比Java、Scala与Python在执行性能、生态结合、开发效率和维护成本上的核心差异,给出清晰的架构选型依据与落地方案。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。