简体   繁体   English

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

[英]How to put a background image in a JFrame?

I'm trying a little JFrame because I have to make the flappy bird project and there's a bug in my code.我正在尝试一点JFrame因为我必须制作 flappy bird 项目并且我的代码中有一个错误。

When I run it, it opens at maximized window but the background picture doesn't load.当我运行它时,它以最大化 window 打开,但背景图片不加载。 I have to minimize the window then maximize it for it to work.我必须最小化 window 然后最大化它才能工作。

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));
    }
}

How can I fix it?我该如何解决?

Try this example:试试这个例子:

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);

Alternatively, another great way to achieve your goal would be to use Background Panel .或者,实现目标的另一种好方法是使用Background Panel

And please, try to avoid using absolute paths, they almost always break the Application when changing directories or systems.请尽量避免使用绝对路径,它们在更改目录或系统时几乎总是会破坏应用程序。

Let me know if that helped:)让我知道这是否有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM