Pradip Kharbuja
Pradip Kharbuja

Reputation: 3542

Java paint error during maximizing JFrame

I've following code to paint in JFrame.

package march_2013;

import java.awt.Graphics;
import javax.swing.JFrame;

public class Question7 extends JFrame {

    public void paint(Graphics g) {
        int[] x = new int[] { 10, 60, 360, 410, 210, 210, 260, 210, 190, 160,
                190, 190 };
        int[] y = new int[] { 200, 250, 250, 200, 200, 180, 180, 100, 100, 160,
                160, 200 };
        g.drawPolygon(x, y, x.length);
        g.drawLine(190, 100, 190, 180);
        g.drawLine(210, 100, 210, 180);
    }

    public static void main(String[] args) {
        Question7 window = new Question7();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setBounds(440, 40, 420, 400);
        window.setVisible(true);
    }
}

It works fine gives following output.

enter image description here

But I maximize the JFrame, the image is repainted. But old image remains as it.

enter image description here

How to solve this problem? Thank you!

Upvotes: 0

Views: 227

Answers (2)

johnchen902
johnchen902

Reputation: 9599

Invoke super.paint().

public void paint(Graphics g) {
    super.paint(g);
    // ...

The API document of paint said:

If this method is reimplemented, super.paint(g) should be called so that lightweight components are properly rendered.

To make sure the background is white:

public void paint(Graphics g) {
    super.paint(g);
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.BLACK);
    // ...

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347244

  1. You should be calling super.paintXxx
  2. You should avoid overriding the paint method of the top level containers (like JFrame) and instead, using something like JPanel and override it's paintComponent method. The main reasons are; 1- top level containers aren't double buffered, meaning you will get flicker as the component is repainted. 2- you can prevent other content from been painted correctly (like not calling super.paint.

Check out Custom Painting and Painting in AWT and Swing for more details

Upvotes: 1

Related Questions