有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我的绘画组件画了一些我没有编码的东西

我做了一个大的水立方,但不知怎么的,在我的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, 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);
    }
    
    
}

我的作品:

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绘画,我看不到这里的bug


共 (0) 个答案