简体   繁体   English

如何完全重新绘制 Java 框架的画布?

[英]How can I completely repaint the canvas of a Java frame?

I am using AWT in Java to create animated frame.我在 Java 中使用 AWT 来创建动画帧。 It is composed of a Frame and a Canvas , as well as some other components.它由FrameCanvas以及其他一些组件组成。 The code basically is:代码基本上是:

public class MyFrame extends Frame implements Runnable{

     private Canvas c = new Canvas();
     public  MyFrame(){

        c.setSize(100, 100);
        this.setSize(100, 100);
        this.add(c);
     }

}

Now I want to draw a part of an image on the canvas.现在我想在画布上绘制图像的一部分。 I tried using the frame's paint method:我尝试使用框架的paint方法:

public void paint(Graphics g){

     Graphics canvasG = c.getGraphics();
     canvasG.drawImage(img, x1, y1, w1, h1, x2, y2, w2, h2, null);

{

This draws the part of the picture, over the part that has been drawn previously.这将绘制图片的一部分,覆盖先前绘制的部分。 I, however, want to repaint the canvas completely.但是,我想完全重新绘制画布。

Wow.哇。 To answer your question:回答你的问题:

  • Don't draw in the class that extends Frame but rather in the paint method of a class that extends Canvas.不要在扩展Frame的类中绘制,而是在扩展Canvas的类的paint方法中绘制。 In other words, create a class called MyCanvas that extends Canvas and give it a paint method override.换句话说,创建一个名为 MyCanvas 的类来扩展 Canvas 并为其提供一个绘制方法覆盖。
  • Create an object of this class and add it to the Frame so it can be displayed.创建此类的对象并将其添加到 Frame 以便可以显示。
  • The first call in your Canvas class's paint method override should be the super method, super.paint(g) . Canvas 类的paint 方法覆盖中的第一个调用应该是super 方法, super.paint(g) This will redraw the Canvas erasing things that need to be erased.这将重新绘制 Canvas 擦除需要擦除的东西。
  • Don't use getGraphics to get a Graphics object from a component since the object obtained will not persist causing bad side effects (try this and then minimize and restore your GUI to see what I mean).不要使用 getGraphics 从组件中获取 Graphics 对象,因为获得的对象不会持续存在,从而导致不良副作用(尝试此操作,然后最小化并恢复您的 GUI 以了解我的意思)。
  • Instead use the Graphics object obtained from the JVM and passed into the paint method.而是使用从 JVM 获取并传递给paint方法的Graphics对象。
  • The exception to this is when working with BufferedImages.使用 BufferedImages 时例外。 For them, yeah, go ahead and get the graphics object via getGraphics() when you need, it, but just don't forget to dispose of it when you're done so as not to run out of system resources.对他们来说,是的,继续并在需要时通过getGraphics()获取图形对象,但不要忘记在完成后处理它,以免耗尽系统资源。

Have fun.玩得开心。

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

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