JComponent 一旦离开屏幕就停止渲染

2023-12-01

我正在尝试制作一个简单的动画,其中一个矩形从屏幕开始(在屏幕右边缘的右侧)并向左移动。因此,在本例中,我的框架的宽度为 1000,墙壁的 x 值为 1100。显然,首先,矩形不应该是 我们可见。但当矩形向左移动时,它最终应该变得可见。然而,这个动画并没有这样做。即使墙的 x 值在屏幕范围内,它也不会被渲染。

我尝试放一个println()中的声明paintComponent()墙的方法,我发现paintComponent()没有被框架调用repaint()方法。我认为当墙第一次添加到框架中时,Swing 认为由于它不在屏幕上,所以不需要渲染,因此即使墙最终出现在屏幕上,Swing 也认为它不需要渲染得到渲染。

我尝试过重新验证和无效框架和组件,但没有任何效果。请帮我解决这个问题。下面是代码:

package graphics.simpleAnimation;

public class Simple_Animation implements Runnable {

    private UI ui; // The UI (frame)

    private Wall wall; // Wall object that moves across the screen

    private Simple_Animation() {

        // Initialize the wall object (intentionally given an x value that is greater than the frame's width)
        wall = new Wall(1100, 400, 200, 400);

        // Initialize the UI (width is only 1000)
        ui = new UI(1000, 600, "Geometry Dash");

        // Add the wall to the ui (the frame)
        ui.add(wall);

    }

    public void run() {
        // Set the frame visible
        ui.setVisible(true);

        // Repaint the frame and move the wall
        while (true) {
            ui.repaint();
            wall.moveWall(-2, 0);

            try {
                Thread.sleep(16);
            } catch (InterruptedException IE) {
                System.out.println(IE);
            }

        }

    }

    // Starts the program in a new thread
    public static void main(String[] args) {
        Simple_Animation simpleAnimation = new Simple_Animation();
        new Thread(simpleAnimation).start();
    }

}


package graphics.simpleAnimation;

import javax.swing.*;
import java.awt.*;

public class UI extends JFrame {

    // Variables storing the width and height of the content pane (where the components are being rendered)
    public int content_pane_width;
    public int content_pane_height;

    public UI(int frameW, int frameH, String frameTitle) {

        setTitle(frameTitle);
        setSize(frameW, frameH);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(null);

        content_pane_width = getContentPane().getWidth();
        content_pane_height = getContentPane().getHeight();

    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
    }

}

package graphics.simpleAnimation;

import java.awt.*;
import javax.swing.*;

public class Wall extends JComponent {

    private int wallX;
    private int wallY;
    private int wallW;
    private int wallH;


    Wall(int x, int y, int sizeX, int sizeY) {
        wallX = x;
        wallY = y;
        wallW = sizeX;
        wallH = sizeY;

        setSize(getPreferredSize());
    }

    public void moveWall(int moveX, int moveY) {
        wallX += moveX;
        wallY += moveY;
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(wallW, wallH);
    }

    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;

        setLocation(wallX, wallY);
        g2d.fillRect(0, 0, wallW, wallH);
    }
}

我在你的程序中发现了一些错误

  1. 您正在使用null layout, 请参见空布局是邪恶的以及答案这个问题看看为什么你应该避免使用它。(可能不是在这种情况下,根据下面的 @MadProgrammer 的评论),这只是另一种方法

  2. while (true) {这条线可能会阻塞事件调度线程 (EDT)沿着这一行:Thread.sleep(16);, See 课程:Swing 中的并发了解更多关于和如何使用 Swing 定时器。您还应该将您的程序放在 EDT 上,可以这样做:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Your constructor here
            }
        });
    }
    
  3. 你没有打电话super.paintComponent()在你的paintComponent()的方法Wall可能会破坏绘画链的类,总是先调用它。

  4. 你正在延长JComponent,最好延长JPanel并使用在其上进行自定义绘画Shapes API

考虑到上述所有内容,您就可以编写如下代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SingleAnimation {

    private JFrame frame;
    private Timer timer;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SingleAnimation().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        Wall wall = new Wall(300, 0);

        timer = new Timer(16, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                wall.moveWall(-2, 0);
            }
        });

        timer.setInitialDelay(0);
        timer.start();

        frame.add(wall);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class Wall extends JPanel {
    private int xCoord;
    private int yCoord;

    public int getxCoord() {
        return xCoord;
    }

    public void setxCoord(int xCoord) {
        this.xCoord = xCoord;
    }

    public int getyCoord() {
        return yCoord;
    }

    public void setyCoord(int yCoord) {
        this.yCoord = yCoord;
    }

    public Wall(int x, int y) {
        this.xCoord = x;
        this.yCoord = y;
    }

    public void moveWall(int xUnits, int yUnits) {
        xCoord += xUnits;
        yCoord += yUnits;
        repaint();
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 400);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.BLUE);

        g2d.fill(new Rectangle2D.Double(xCoord, yCoord, 100, 20));
    }
}

这将产生类似的输出,如下所示:

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JComponent 一旦离开屏幕就停止渲染 的相关文章

随机推荐

  • 调用方法后如何在标准输出中写入(自动执行通知系统(Iphone))

    我正在尝试使用自动通知系统 Iphone https github com simonwhitaker PyAPNs 当您想要发送通知时 您可以调用 apns gateway server send notification key Pay
  • bluebirdjs 承诺包裹在 for 循环中

    我有很多函数用于向我的服务提供数据 我想循环遍历它们中的每一个 并在其中一个返回所需结果时立即停止 如果第一个有效 那很好 如果有异常或数据无效 我想转到下一个 依此类推 我怎样才能实现这个目标 我有以下代码 handleData func
  • Facebook“赞”按钮回调

    我对实现 facebook 喜欢 按钮感兴趣 但我想知道哪些用户正在单击此按钮 以便我可以从中获取一些有用的信息 据我所知 Facebook 让我们对谁在点击什么一无所知 有人知道如何跟踪哪个用户点击了特定产品的 喜欢 按钮吗 更新 赞 按
  • 如何将对象存储在 firebase cloud function RAM 中?

    我的应用程序需要在处理用户的请求之前构建几个大型哈希图 理想情况下 我想将这些哈希图存储在机器的内存中 这意味着它永远不需要进行任何昂贵的处理 并且可以快速处理任何传入的请求 但这对于 Firebase 不起作用 因为用户有可能触发一个新实
  • 将运行 EXE 的当前 Windows 用户替换为另一个用户

    假设我构建了一个从网络文件夹读取文件的 Windows 应用程序 网络折叠限制只有一个用户 fooUser 的访问 该应用程序安装在网络上的多台计算机上 我需要将当前用户替换为 fooUser 以便能够通过代码访问网络文件夹上的文件 这是一
  • 如何以字幕方式输出字符串?

    我希望能够输入一个字符串 带空格 并将其显示为移动符号 例如 Input Hello World 5 This signifies the number of characters the sign can hold Output Sign
  • arr.sort(key=lambda x: (x[0],-x[1])) 是什么意思?

    gt gt gt arr 4 5 4 6 6 7 2 3 1 1 gt gt gt arr sort key lambda x x 0 statement 1 gt gt gt arr 1 1 2 3 4 5 4 6 6 7 gt gt g
  • CSS 在背景图像上模糊,但在内容上不模糊 [重复]

    这个问题在这里已经有答案了 I did 这个例子 我试图模糊背景图像 但主要内容也模糊了 span 如何在不模糊内容的情况下模糊背景 jsfiddle blur bgimage overflow hidden margin 0 text a
  • 如何用mongoosastic+AJAX进行即时搜索?

    我已经成功配置了 mongoosastic 我尝试搜索并且工作正常 但是当涉及到前端时我不太确定如何实现这一点 我尝试了很多方法但无法想出一个好的解决方案 这是代码 For the Search API router post api se
  • 从 VBA 执行 SQL Server 存储过程并检索所有消息和结果集

    我希望能够从 MS Access VBA 执行 SQL Server 存储过程 这样我就可以读取 1 所有结果结果集 而不仅仅是第一个结果集 2 由 PRINT 语句或类似语句产生的任何消息 我有一个带有一个输入参数的测试存储过程 它会生成
  • 如何让 MySQL 在查询中提示输入值? [关闭]

    很难说出这里问的是什么 这个问题模棱两可 含糊不清 不完整 过于宽泛或言辞激烈 无法以目前的形式合理回答 如需帮助澄清此问题以便重新打开 访问帮助中心 我在 MySQL 控制台中对一些 SQL 查询进行了大量的试验和错误 例如 select
  • 查询生成器在字段类型数组上添加条件

    我的问题很简单 是否可以使用原则和查询生成器在字段类型数组上添加 where 语句 在我的实体内 我有以下内容 var array ORM Column name weekDays type array private weekDays 在
  • PHP 世博会推送通知

    我正在尝试使用 PHP 向我的 React Native 应用程序发送推送通知 下面的代码也发送了所有注册其令牌的用户 并且它一次发送了大量通知 尽管该令牌适用于特定设备 但它不断将通知推送给所有用户 key ExponentPushTok
  • 在 mongoose/mongodb/node 中使用异步回调循环

    我是 nodejs mongo mongoose 的新手 我正在尝试做一件非常简单的事情 我有以下架构 var authorSchema mongoose Schema name String Author mongoose model A
  • DrawingArea无法获取XID

    我有以下 Python 2 7 PyGObject 3 0 PyGST 0 10 模块 from gi repository import Gtk Gdk GdkPixbuf import pango import pygst pygst
  • 使用 WPF C# 打印

    我的应用程序将屏幕上显示的信息 使用 Canvas 控件 打印 到打印机 N 次 过程是 用户单击一个按钮 称为 打印 用文本更新画布 通常来自数据库 但对于下面的代码 它是硬编码的 打印到打印机使用新文本更新画布 同样来自数据库 但对于下
  • 在 React 中,本机“adb”不被识别为内部和外部命令

    我尝试在环境变量中设置路径 但它不起作用 错误如下 adb 不被识别为内部或外部命令 可运行的程序或批处理文件 启动应用程序 C Users Administrator AppData Local Android Sdk platform
  • j2me - 如何创建主从 UI

    我陷入了 j2me 项目的中间 因为我不知道如何做一些在其他平台上很容易完成的事情 但这似乎在 java me j2me 中没有直接的解决方案 我需要做的是这个 无论是使用Netbeans MIDP组件 LWUIT还是纯lcdui都没关系
  • C# MySql 创建用户

    我试图用 C 来做一个注册声明 显然我没能做到 我不知道问题是什么 话虽如此 这里是一个片段 MySqlConnection Connection new MySqlConnection SERVER localhost UID root
  • JComponent 一旦离开屏幕就停止渲染

    我正在尝试制作一个简单的动画 其中一个矩形从屏幕开始 在屏幕右边缘的右侧 并向左移动 因此 在本例中 我的框架的宽度为 1000 墙壁的 x 值为 1100 显然 首先 矩形不应该是 我们可见 但当矩形向左移动时 它最终应该变得可见 然而