You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Swing开发Pong游戏时JFrame空白 Graphics绘制无效果

问题根因
  • 核心错误:自定义Pintar类的绘制方法名不符合Swing规范。JPanel的自动回调绘制方法为paintComponent(Graphics g),你自定义的pintar(Graphics g)方法不会被Swing渲染流程调用,因此没有任何内容显示。
  • 缺失编译校验:重写父类方法时未添加@Override注解,无法在编译阶段提前发现方法名、参数不匹配的错误。
  • 额外异常点:setBackground(null)会将窗口背景设为透明,可能干扰正常渲染;Swing组件初始化未放在事件调度线程(EDT)中执行,存在线程安全导致的渲染异常风险。
修复后的完整代码
import java.awt.*;
import javax.swing.*;

public class Pong extends JFrame {
    int ancho = 800;
    int alto = 800;
    Point barra1 = new Point((int) (ancho*0.05), (int) alto/2);
    Point barra2 = new Point((int) (ancho*0.95), (int) alto/2);
    boolean gameover = true;
    Pintar pintar;

    public Pong(){
        setTitle("Pong");
        Pintar elementos = new Pintar();
        this.getContentPane().add(elementos);
        setSize(ancho,alto);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFrame.setDefaultLookAndFeelDecorated(false);
        setUndecorated(true);
        this.setLocationRelativeTo(null);
        setVisible(true);
    }

    public class Pintar extends JPanel{
        // 修正方法名,添加@Override注解
        @Override
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            if(gameover){
                g.setColor(Color.BLACK);
            }
            else{
                g.setColor(Color.WHITE);
            }
            // 优先使用组件自身宽高,适配窗口大小变化
            g.fillRect(0, 0, getWidth(), getHeight());
        }
    }

    public static void main(String[] args) {
        // Swing组件初始化放在EDT线程执行,避免线程安全问题
        SwingUtilities.invokeLater(() -> {
            Pong pantalla1 = new Pong();
        });
    }
}

运行修复后代码,gameover为true时窗口会显示全屏黑色,符合预期绘制逻辑。

内容的提问来源于stack exchange,提问作者Jesús Carrasquer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:54:03