简体   繁体   English

您如何在Java中更新此自定义绘画?

[英]How do you update this custom paint in Java?

I have a GUI based game that is real time and uses a JPanel and JFrame. 我有一个基于GUI的实时游戏,并使用JPanel和JFrame。 I currently have a overridden paintComponent which paints based on certain conditions in my code. 我目前有一个重写的paintComponent,它根据代码中的某些条件进行绘制。 For example: 例如:

protected void paintComponent(Graphics gfx)
{
    super.paintComponent(gfx);
    gfx.setFont(new Font("default", Font.BOLD, 18));

    if (one)
    {
        //do something
    }

    else
    {
        // do something else
    }
}

This works once depending on the condition. 这取决于条件一次。 I have implemented a mouse listener that I'd like to use for the statements so that if someone clicks on a certain part it shows something else. 我已经实现了一个鼠标侦听器,我想将其用于语句,这样,如果有人单击某个部分,它将显示其他内容。 I'd like to go back and run the paintComponent again so that it paints over top of the old one. 我想返回并再次运行paintComponent,以便在旧的组件上绘制。 Does paintComponent() already loop? paintComponent()是否已经循环? If not, how can you run the method in a loop? 如果没有,如何循环运行该方法?

You can repaint by calling repaint() . 您可以通过调用repaint()来重绘。 You can do this in a loop by creating a timer to repaint it, or just call it when it needs to be updated (probably better if your code is simple enough) 您可以通过创建一个计时器来重绘它来循环执行此操作,或者仅在需要更新它时调用它(如果您的代码足够简单,则可能会更好)

EDIT: About when to use a timer: 编辑:关于何时使用计时器:

The timer is not necessary. 不需要计时器。 I used it in a game once because I was custom painting the entire window and there were dozens of always-changing things to paint, and calling render() every time would not make my CPU happy. 我曾经在游戏中使用过它,因为我是自定义绘制整个窗口的内容,并且要绘制数十种随时变化的内容,每次调用render()都不会使我的CPU感到高兴。 For something simple, though, it is better to call repaint() only when something changes, because if nothing changed, you are wasting that much time repainting it. 但是,对于简单的事情,最好仅在发生更改时才调用repaint() ,因为如果没有任何更改,那么您将浪费大量时间进行重新绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM