Search code examples
javaswingjpanelpaintcomponentdoublebuffered

Extending JPanel, What Gets Carried Over


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();

    }

}

Solution

    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.