【问题标题】:Image not loading/updating图片未加载/更新
【发布时间】:2025-12-16 04:15:01
【问题描述】:

这是这个程序的代码。如果我在 public void paintComponent(Graphics g) {} 方法中加载图像,图像会加载,但是如果我从另一个类加载它们,它们不会。

主类:

public class main {

    static GUI GUI = new GUI();
    static render render = new render();
    static loader loader = new loader();

    public static void main(String [] args) {
        frame.start();
        loader.start();

    }
}

框架类:

public class GUI implements Runnable {

    public void start() {
        new Thread(this).start();
    }

    public void run(){ 
        JFrame frame = new JFrame(); 
        System.out.println("frame starting");
        frame.setSize(700,600); 
        frame.setResizable(false); 
        frame.setLocationRelativeTo(null);
        frame.setTitle("Project ");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.addMouseListener(render);
        frame.add(render);
        frame.setVisible(true);
    }
}

渲染类

public class render extends JPanel implements ActionListener {

    Timer tm = new Timer(7, this);
    loader loader = new loader();

    public render() {
        tm.start();
    }

    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(loader.Getbackground(), -100,-400,null);

    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

加载器类

public class loader implements Runnable {

    Image background;

    public void start() {
        new Thread(this).start();
    }

    public void run() {
        ImageIcon backgroundhold = new ImageIcon(render.class.getResource("resources/Background.png"));
        background = backgroundhold.getImage();
        setbackground(background);
    }

    public void setbackground(Image background) {
        this.background = background;

    }

    public Image Getbackground() {
        return background;
    }

    public void setbackground(Image background){
        this.background = background;

    }
}

当程序启动时,它会打开一个没有图像的空框架。我做错了什么?

阿伦

【问题讨论】:

  • 您的代码必须经过审核,您甚至没有在 Render 类中打开 {,没有声明字段 frame ...
  • 抱歉代码是手动添加的,我可能忘记添加部分代码了。

标签: java image


【解决方案1】:

请注意,绘图程序 SHOULD 会覆盖 paintComponent() 以绘制/加载/...图像

所以如果你想在另一个类中加载图像,它应该扩展 Jpanel 并覆盖paintComponent(),就像你对渲染类所做的那样。

【讨论】:

  • 好的,所以我应该删除加载器类并在public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(loader.Getbackground(), -100,-400,null); 中加载图像?这就是我最初的做法,但我认为在另一个线程中加载图像会导致在图像加载之前屏幕上的“白色”较少
  • 你可以创建新的线程来加载图像,它实现了 Runnable 并扩展了 Jpanel,然后在 run 方法中你可以覆盖 paintComponent 方法并加载你的图像