Java - 如何显示图像?

标签 java image jframe jlabel imageicon

我花了很长时间试图找到一种在 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();
        }

    }

}

这是新代码的效果: enter image description here

希望有帮助。

顺便说一句,我已将图像放在项目的根目录中。

关于Java - 如何显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32490876/

相关文章:

java - JFrame 'Console' 样式文本

java - dao层空指针异常

html - 调整移动设备背景图像的大小

html - 如何将文本和图像对齐在一行上并将它们放置在左侧和/或右侧?

jquery - mouseenter 和 mouseleave 在 jquery 中不起作用

Java JFrame BufferStrategy 与 Canvas BufferStrategy

java - 动物园管理员 : how to correctly reconnect when session expired?

java - 如果有未提交的更改,Maven 会阻止构建

java - 将dll添加到spring mvc项目中

java - JFrame问题