Search code examples
javagraphicspaintpaintcomponentrepaint

Java: Overriding paint() AND paintComponent()


New to java: I overrode paint() and put some things in that; then i overrode paintComponent() and I noticed that the code in paint() isn't being run. Did i forget to do something or am i just ignorant? (I know it's good practice to use @override, but it's one of those days)

private Image dbImage;
private Graphics dbg;

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

    g.fillOval(0, 0, 10, 12);
}
public void paintComponent(Graphics g) {
    setBackground(Color.CYAN);

    double i = .25;
    if (du) {
        y -= i;
    }
    if (dr) {
        x += i;
    }
    if (dd) {
        y += i;
    }
    if (dl) {
        x -= i;
    }

    if (x < 0) {
        x = 0;
    }
    if (x > getWidth() - 25) {
        x = getWidth() - 25;
    }
    if (y < 25) {
        y = 25;
    }
    if (y > getHeight() - 25) {
        y = getHeight() - 25;
    }

    g.drawOval( (int) x, (int) y, 25, 25);
    repaint();

}
public static void main(String[] args) {


}

And on an unrelated topic: what does repaint() do?


Solution

  • Don't override paint() and don't invoke a painting method directly. The Swing painting mechanism will make sure the proper painting methods are ivoke at the proper time.

    Custom painting is done by overriding paintComonent(...) of a JPanel (or JComponent). Then you add the panel to the frame.

    Read the section from the Swing tutorial for more information and working examples.

    what does repaint() do?

    It schedules a repainting of the component. The RepaintManager will consolidate repaint requests into a single paint request to make painting more efficient.

    You should NEVER invoke repaint() in a painting method. You invoke repaint() in a setter method when you change a property of the class. For example using methods like setForeground(), setBackground() would cause a repaint() of the component.

    New to java:

    I suggest you keep a link to the Swing tutorial handy for learning Swing basics.