我的paintComponent绘制了一些我没有编写的代码

问题描述

我做了一个大的水色方块,但是不知何故,我的JPanel中出现了一个灰色的小方块,看起来像这样。

enter image description here

中间有一个灰色的小方块,我没有画出来。如何避免呢?这是我的代码

我的主:

package Main;

public class main {
    
    public static void main(String[] args) {
        createWindow window = new createWindow();
        
    }

}

myFrame和myPanel:

package Main;

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

public class createWindow extends JFrame {
    
    public myPanel panel;
    
    public createWindow() {
        super();
        panel = new myPanel();
        KeyListener key = new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
                
                
                
            }

            @Override
            public void keypressed(KeyEvent e) {
                
                
                
            }

            @Override
            public void keyreleased(KeyEvent e) {
                
                keyAction(e.getKeyCode());
                
            }
            public void keyAction(int keycode) {
                switch (keycode) {
                    case KeyEvent.VK_UP:
                        System.out.println("Up");
                        break;
                    case KeyEvent.VK_RIGHT:
                        System.out.println("Right");
                        break;
                    case KeyEvent.VK_DOWN:
                        System.out.println("Down");
                        break;
                    case KeyEvent.VK_LEFT:
                        System.out.println("Left");
                        break;
                }
            }
            
        };
        
        pack();
        add(panel);
        addKeyListener(key);
        setSize(800,450);
        setResizable(false);
        setLocationRelativeto(null);
        setVisible(true);
        
    }
    
}

class myPanel extends JPanel {
    public Piece firstP = new Piece(100,100,new Color(50,255,255),"self");
    
    myPanel() {
        super();
        
        setBackground(Color.gray);
        add(firstP);
    }
    
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        
        g2d.setColor(firstP.color);
        g2d.fillRect(firstP.x,firstP.y,firstP.width,firstP.height);
    }
    
    
}

myPiece:

package Objects;

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

public class Piece extends JPanel {
    
    public int x;
    public int y;
    public int width;
    public int height;
    public Color color;
    public String type;
    
    public Piece(int x,int y,int width,int height,Color color,String type) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.color = color;
        this.type = type;
    }
    
    
}

有人可以修复我的代码吗?我是java绘画的新手,在这里看不到错误...

解决方法

如果删除显示“ add(firstP);”的行,则灰色小方框消失。