如何在 JFrame 中放置背景图像?

问题描述

我正在尝试一些 JFrame,因为我必须制作飞扬的小鸟项目,而且我的代码中存在一个错误

当我运行它时,它在最大化的窗口中打开,但没有加载背景图片。我必须最小化窗口然后最大化它才能工作。

package com.company;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Main extends JFrame{
    JButton button;
    JLabel text;
    JFrame frame;
    JPanel panel;

    public static void main(String[] args) {
        new Main();
    }

    public Main(){
        setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("flappyBird");
        setLocationRelativeto(null);
        setVisible(true);
        setSize(new Dimension(100,100));
        setExtendedState(JFrame.MAXIMIZED_BOTH);

        BufferedImage img = null;
        try {
            img = ImageIO.read(new File("C:\\Users\\m11\\Documents\\FlappyBird\\spirit\\base.png"));
        } catch (IOException e) {
            e.printstacktrace();
        }
        Image dimg = img.getScaledInstance(800,508,Image.SCALE_SMOOTH);
        ImageIcon imageIcon = new ImageIcon(dimg);
        setContentPane(new JLabel(imageIcon));
    }
}

我该如何解决

解决方法

试试这个例子:

JFrame f = new JFrame();
try {
    f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
} catch (IOException e) {
    e.printStackTrace();
}
f.pack();
f.setVisible(true);

或者,另一种实现目标的好方法是使用 Background Panel

请尽量避免使用绝对路径,它们在更改目录或系统时几乎总是会破坏应用程序。

让我知道这是否有帮助:)