简体   繁体   English

Java Swing - 闪烁的Canvas图形

[英]Java Swing - flickering Canvas graphics

I have to write a simple Java app which can load pictures, show it in a GUI form, allow the user to apply some transformation, and show the transformed picture. 我必须编写一个简单的Java应用程序,它可以加载图片,以GUI形式显示,允许用户应用一些转换,并显示转换后的图片。 My solution is working fine, but the UI is flickering a bit, because the repaint method called too often (for example when the user scaling the image with a JSlider) 我的解决方案工作正常,但UI有点闪烁,因为重绘方法调用太频繁(例如当用户使用JSlider缩放图像时)

My code looks like this: 我的代码看起来像这样:

public class ImageCanvas extends Canvas
{
    private BufferedImage image;
    // ...

    @Override
    public void paint(Graphics g) 
    {
        Graphics2D g2d = (Graphics2D) g;
        if(image != null)
        {
             // I draw out the image...
        }
    }

    public void setImage(BufferedImage image)
    {
        this.image = image;
        this.repaint();
    }

    public void setRotation(double rotation)
    {
        this.rotation = rotation;
        this.repaint();
    }

    public void setScale(double scaleX, double scaleY) 
    { 
       //set the scaling field, then repaint ....
    }    

    // and so on...
}

And, of course, I have an ImageCanvas control on my main UI, and I simply call the public methods (see for example the "setRotation" method above) which repaint the canvas area. 当然,我在我的主UI上有一个ImageCanvas控件,我只是调用公共方法(参见上面的“setRotation”方法),它重绘了画布区域。 I know it's a simple question, but I don't even find a DoubleBuffered property on the Canvas... 我知道这是一个简单的问题,但我甚至没有在Canvas上找到DoubleBuffered属性......

Any help appreciated. 任何帮助赞赏。

Double buffering is built-in for Swing (ie JComponent derived) classes. 双缓冲内置于Swing(即JComponent派生)类。

If you want built-in double-buffering, you should extend JPanel rather than Canvas, and override paintComponent , not paint . 如果你想要内置的双缓冲,你应该扩展JPanel而不是Canvas,并覆盖paintComponent ,而不是paint

If you can use JPanel than go for it. 如果你可以使用JPanel不是它。 Please make sure you are not overriding the JPanel.paint method, override JPanel.paintComponent instead. 请确保您没有覆盖JPanel.paint方法,而是覆盖JPanel.paintComponent See this link for details. 请参阅此链接了解详情。

Usually graphic lags in these applications can be caused by setting a empty variable at the top of the script, then changing its value, then waiting for the repaint to update it. 通常,这些应用程序中的图形滞后可能是通过在脚本顶部设置一个空变量,然后更改其值,然后等待重绘更新它来引起的。 You could try changing the: 您可以尝试更改:

    setRotation(double rotation);

so that it rotates the image in that method. 以便它以该方法旋转图像。

Just a general thing I happen to see while dealing with graphics. 在处理图形时,我偶然会看到一般情况。

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

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