我花了很长时间试图找到一种在 Java 程序中显示图像的方法(我正在尝试学习如何制作 2D Java 游戏),但我尝试过的任何方法都不起作用。我正在使用 Eclipse Mars 和其他最新的产品。这是我的代码:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public static void main(String[] args0) {
JFrame frame = new JFrame();
ImageIcon image = new ImageIcon("background.bmp");
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
frame.setLayout(null);
imageLabel.setLocation(0, 0);
imageLabel.setSize(1000, 750);
imageLabel.setVisible(true);
frame.setVisible(true);
frame.setSize(1000, 750);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
请告诉我如何更正代码以使图像实际显示。提前谢谢您。
(P.S.如果有任何改变,“background.bmp”文件位于“默认包”中)
最佳答案
您的代码中无法显示带有.bmp后缀的图像。尝试修改
ImageIcon image = new ImageIcon("background.bmp");
至
ImageIcon image = new ImageIcon("background.png");
并将图像名称更改为background.png。
但是,如果您只想使用background.bmp,则需要像这样修改代码,背景图像就会显示。
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
File imageFile = new File("background.bmp");
Image i = ImageIO.read(imageFile);
ImageIcon image = new ImageIcon(i);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
frame.setLayout(null);
imageLabel.setLocation(0, 0);
imageLabel.setSize(1000, 750);
imageLabel.setVisible(true);
frame.setVisible(true);
frame.setSize(1000, 750);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
希望有帮助。
顺便说一句,我已将图像放在项目的根目录中。
关于Java - 如何显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32490876/