سؤال

So I created an abstract JPanel called BasePanel. In it I i use a double buffer code like so:

public void paint(Graphics g) {
    dbImage = createImage(getWidth(), getHeight());
    dbg = dbImage.getGraphics();
    paintComponent(dbg);
    g.drawImage(dbImage, 0, 0, this);
    repaint();
}

public void paintComponent(Graphics g) {
    g.setColor(Color.BLACK);
}

And then when extending it on another panel, i was wondering would it still double buffer if i only Overrode the paintComponent method? So I wouldnt even need to call the paint method

An Example

public class StartScreen extends BasePanel {
    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, getWidth(), getHeight());

        g.setColor(Color.WHITE);
        g.drawString("Animation Screen", 175, 150);;

        repaint();

    }

}
هل كانت مفيدة؟

المحلول

  1. Don't override paint();
  2. Don't invoke repaint() in any painting method.
  3. Don't use the getGraphics() method, you already have the Graphics object
  4. Custom painting is done in the paintComponent() method and don't forget to invoke super.paintComponent(...)

Double buffering is automatically inherited from the parent component.

نصائح أخرى

Sorry but yours is terrible "double buffering" code. Just override paintComponent and you're double buffered. Never call repaint in paint or paintComponent! Don't override paint unless you mean to change how borders and children are painted.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top