有 Java 编程相关的问题?

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

java我正在尝试给JPanel窗口背景上色。但我在执行后得到了一个没有任何颜色的JPanel窗口。代码中有什么错误?

我正在给JPanel窗口的背景上色。但我在处决后得到了一个没有任何颜色的JPanel窗口。代码中有什么错误

package BrickBreaker;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;
import javax.swing.Timer;

public class Gameplay extends JPanel {

    private boolean play = false;
    private int totalBrick = 28;
    private Timer time;
    private int delay = 8;
    private int ballPosX = 120;
    private int ballPosY = 350;
    private int ballXdir = -1;
    private int ballYdir = -2;
    private int playerX = 350;

    public Gameplay() {

    }

    public void paint(Graphics g) {
        g.setColor(Color.black);
        g.fillRect(1, 1, 692, 592);
    }

}

共 (1) 个答案

  1. # 1 楼答案

    你应该这样做(我假设你有一个添加了面板的JFrame)

    public class Gameplay extends JPanel {
    
        private boolean play = false;
        private int totalBrick = 28;
        private Timer time;
        private int delay = 8;
        private int ballPosX = 120;
        private int ballPosY = 350;
        private int ballXdir = -1;
        private int ballYdir = -2;
        private int playerX = 350;
    
        public Gameplay() {
            setBackground(Color.black);
        }
    
        // if your going to override this you need to call the parent's paintComponent.
        // otherwise the setBackground would not work.
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
           g = g.create();
           // g.setColor(Color.black);// you don't need this
           // g.fillRect(1, 1, 692, 592); // now you don't need this
           // But if you want to draw a red circle, you do need to change the color
           // for that
           g.setColor(Color.red);
           g.fillOval(100,100,50,50);
           g.dispose();
        }
    
    }