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

BufferedImage可加载但无法绘制的Java Swing技术问题求助

解决Swing中BufferedImage无法绘制到界面的问题

问题代码

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;
import javax.swing.Timer;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MainCasino extends JPanel{
    Random ra = new Random();
    Scanner sc = new Scanner(System.in);
    DrawingPanel pane;
    JFrame window;
    Timer timer;
    
    BufferedImage bg = loadImage("Casinobg.png");
    
    final int PANW = 900;
    final int PANH = 700;
    final int T_SPEED = 15;
    
    int prob;
    int result;

    public static void main(String[] args) {
        new MainCasino();
    }
    
    MainCasino(){
        setupGUI();
        monkeyBusiness();
    }
    
    void setupGUI() {
        window = new JFrame("SLOT MACHINE");
        window.setPreferredSize(new Dimension(PANW, PANH));
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);
        
        pane = new DrawingPanel();
        pane.setPreferredSize(new Dimension(PANW, PANH));
        pane.setVisible(true);
        window.add(pane);
        window.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == ' ') {
                    
                }
            }
        });
    }
    void monkeyBusiness() {
        timer = new Timer(T_SPEED, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
                pane.repaint();
            }
        });
        timer.start();
    }
    
    void spin() {
        prob = ra.nextInt(100, 500)+1;
        result = ra.nextInt(prob)+1;
    }
    
    private class DrawingPanel extends JPanel {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            System.out.println("WOmp");
            g.drawImage(bg, 1, 1, PANW, PANH, null);
        }
    }
    
    static BufferedImage loadImage(String filename) {
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File(filename));
        } catch (Exception e) {
            System.out.println(e.toString());
            JOptionPane.showMessageDialog(null, "An image failed to load: " + filename, "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        return img;
    }
}   

问题描述

我已尝试调整图片在项目文件夹中的位置,确认路径无误;修改图片绘制的x、y坐标,问题仍未解决;通过System.out验证Timer处于运行状态,但BufferedImage始终无法绘制到界面上,不清楚问题所在,寻求帮助。


排查与修复步骤

1. 修正窗口组件初始化顺序

你当前先调用window.pack()和window.setVisible(true),之后才添加DrawingPanel到窗口,这会导致组件无法被正确布局渲染。调整setupGUI方法的执行顺序:

void setupGUI() {
    window = new JFrame("SLOT MACHINE");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    // 先添加所有组件
    pane = new DrawingPanel();
    pane.setPreferredSize(new Dimension(PANW, PANH));
    window.add(pane);
    
    window.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
            if (e.getKeyChar() == ' ') {
                
            }
        }
    });
    
    // 最后执行窗口大小计算和显示
    window.pack();
    window.setLocationRelativeTo(null);
    window.setVisible(true);
}

2. 确认图片是否成功加载

在DrawingPanel的paintComponent中添加空值判断,验证bg是否有效:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    System.out.println("WOmp, bg is null? " + (bg == null));
    if (bg != null) {
        g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
    }
}

如果输出bg is null? true,说明图片加载失败:

  • 检查文件名大小写(Linux/macOS区分大小写,Windows不区分)
  • 尝试用绝对路径测试,比如loadImage("C:/项目路径/Casinobg.png")(Windows)或/home/用户名/项目路径/Casinobg.png(Linux/macOS)

3. 优化图片绘制逻辑

把固定尺寸的绘制参数改成适配组件实际大小的写法,同时传入当前面板作为ImageObserver:

g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);

这样能确保图片加载完成后触发重绘,且完全填充面板区域。

4. 移除冗余继承

MainCasino继承了JPanel但未使用,直接去掉继承避免代码混淆:

public class MainCasino { // 移除extends JPanel
    // 原有代码不变
}

内容的提问来源于stack exchange,提问作者SoupMan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:46:36