This square, which I enliven, leaves a trace behind it, can anyone understand why?

Thank you for checking this question. I seem to be just upset in my skull. So, I have a "JFrame" containing a "JPanel". "JPanel" contains a slightly colored square that should move X pixels whenever I click on a window.

Well, in fact, everything behaves as it should, with one exception. When the blue square moves to the right, it leaves a trail of other squares behind it. However, you should not leave a trace when I resize the window, the trace disappears.

Catalyst.java

package Prototype;

import java.awt.*;

public class Catalyst {

public static void main(String[] args){
    World theWorldInstance = new World("Prototype", 100,100, 600,100);  /*title,xpos,ypos,width,height*/
}

}

World.java

package Prototype;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class World extends JFrame  {

Level mainPanel;    

public World(String title, int x, int y, int width, int height) {

    setTitle(title);
    setBounds(x,y,width,height);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBackground(new Color(0x00000000));
    initLevel();

}

public void initLevel(){
    mainPanel = new Level();
    Container visibleArea = getContentPane();
    visibleArea.add(mainPanel);
    setVisible(true);
    add(mainPanel);
}



}

Level.java

package Prototype;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Level extends JPanel implements MouseListener, ActionListener {
Square x;


public Level() {
    System.out.println("This is working correctly[JPANEL Cons]");
    addMouseListener(this);
    x = new Square();
}

public void paintComponent(Graphics g){
    x.draw(g);
}

public void actionPerformed(ActionEvent e){
}

public void mousePressed(MouseEvent e){
    requestFocus();
    x.move();
    repaint();
    System.out.println("Focus Acquired");


}

public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
}

Square.java

package Prototype;

import java.awt.*;

public class Square {

private Point position;
private int size;
private final int displacement;

public Square(){
    position = new Point(10,10);
    size = 20;
    displacement = 5;

}

public void draw(Graphics g){
    g.setColor(Color.blue);
    g.fillRect(position.x-(size/2), position.y-(size/2), size,size );
    g.setColor(Color.black);
    g.drawRect(position.x-(size/2), position.y-(size/2), size,size );

}

public void move() {
    position.x += displacement;
}
}

. , . , - , . , - , - . , !

+3
2

. paintComponent , .

:

this.setBackground(Color.BLACK);

paintComponent:

super.paintComponent(g);
+3

g.clearRect(x, y, width, height) , , . JPanel/JComponent, , , , .

+3

All Articles