java - 如何将背景图像放入 JFrame 中?
问题描述
我正在尝试一点JFrame
,因为我必须制作 flappy bird 项目并且我的代码中有一个错误。
当我运行它时,它会在最大化窗口中打开,但不会加载背景图片。我必须最小化窗口然后最大化它才能工作。
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。
请尽量避免使用绝对路径,它们在更改目录或系统时几乎总是会破坏应用程序。
让我知道这是否有帮助:)
推荐阅读
- resharper - Rehsarper 2018.2.3 Disbale 在摘要和单行注释之间插入新行
- c# - 无法访问控制器外部的 userManager
- css - 固定容器位于身体的滚动顶部
- python - [-1] 和 [0] 在这里有什么用?
- bash - 使用 JSON 响应检查网站是否在线
- android - Google Play 中的内部测试不发送电子邮件
- file - 表单数据:.p7m 文件的内容类型错误
- html - Ionic 3 - 如何使段落的高度与幻灯片高度相同?
- c++ - 如何为 QTreeView 中的特定行制作自定义 QItemDelegate?
- nativescript - tns build android 《app-debug.apk》包太大