Pergunta

I'm drawing many bufferedImage's onto a JFrame using the paint() method,

public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(bufferedImg, x, y, layeredPane);
        ...More images
    }

The problem is it repaints all of the images and so the screen will go blank, then, display the images. I need to repaint a single image, not everything in the paint method. So I tried making another method separate then the paint method and just call that..

public void drawImage(){
    Graphics2D g2d = (Graphics2D) getGraphics();

    if (condition == true) g2d.drawImage(bufferedImg, x, y, layeredPane);
}

And this works to draw the image, but once the boolean is set to false and called, it still keeps the images on the screen. Sorry if this has been posted before, I seen quite a few posts about repainting images in Java, but I couldn't find one that specifically repaints a single image.

Foi útil?

Solução

  1. If your program is a Swing program, then you should not override paint but rather paintComponent(...) of a JComponent derived class.
  2. You can limit the location of the repainted area by calling repaint(Rectangle r), with the Rectangle's bounds being that of the area that you want changed.
  3. You should not get a Graphics context by calling getGraphics() on a component as this will give you a short-lived Graphics object only, and anything drawn with it will be lost in a repaint.
  4. If many of your images don't change, if they act as a background, consider drawing them to one background BufferedImage, and then drawing that one in your paintComponent(...) method.

For more help, consider creating and posting a minimal, compilable, runnable example program.


Edit
Regarding your new post:

I'm drawing many bufferedImage's onto a JFrame using the paint() method

No, never draw directly into the JFrame as you lose many of the benefits of Swing graphics including double buffering, and risk messing up the drawing of borders and child components. You will want to read the Swing custom painting tutorial to learn more on how to draw correctly.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top