Why is it not redrawing ENTIRE JPanel?

Why is it in Java, when I try to move my window from the side of the screen to the center, then the whole JPanel does not redraw it myself?

Example: This is what happened when I tried to drag the window from the side of the screen (only about half the window is visible) to the center:

CrazyHorse

If I add a listener component and then put repaint()in the method componentMoved, it will work fine, but then it will be redrawn every time the window is moved.

Relevant Code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TEST extends JFrame
{

    public TEST()
    {
        super ("TEST!");
        setSize (500,400);
        setLocationRelativeTo(null);
        setContentPane(new MyPanel());
        addComponentListener(this);
    }

    class MyPanel extends JPanel
    {   
        public void paintComponent (Graphics g)
        {

            super.paintComponent(g);

            Graphics g2d =  (Graphics2D) g;

            int R = (int)(Math.random()*256);
            int G = (int)(Math.random()*256);
            int B= (int)(Math.random()*256);
            Color color = new Color(R, G, B);

            g2d.setColor(color);
            g2d.fillOval(0, 0, getWidth(), getHeight());

        }
    }

    public static void main (String[] args)
    {
        TEST t = new TEST();
        t.setVisible(true);
    }
}
+4
source share
1 answer

Interestingly, I have never noticed this before.

. , , , . , , ( ) .

, paintComponent():

 System.out.println(g.getClipBounds());

, , Swing -, .

, , paintComponent(), , , , paintComponent(). .

+6

All Articles