Java:图像不显示

标签 java swing graphics

我正在制作一个需要显示图像的程序。我正在使用 ImageIcon 和 Image 类来执行此操作。我在构造函数中声明了 ImageIcon,然后通过 i.getImage() 分配图像值。除了图像之外的所有内容似乎都加载良好。这是我的代码:

更新:我的图像与代码位于同一目录中。我使用的是 Mac,并且尝试过“image.png”、“./image.png”、“Users/myStuff/Documents/workspace/Game/src/image.png”。这些都没有奏效。

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class Game extends JFrame {

    int x = 100, y = 100;

    private Image dbimage;
    private Graphics dbg;

    Image image;

    class AL extends KeyAdapter {

        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if (keyCode == e.VK_LEFT) {
                if (x <= 20) {
                    x = 20;
                } else {
                    x -= 5;
                }
            } else if (keyCode == e.VK_RIGHT) {
                if (x >= 230) {
                    x = 230;
                } else {
                    x += 5;
                }
            } else if (keyCode == e.VK_UP) {
                if (y <= 20) {
                    y = 20;
                } else {
                    y -= 5;
                }
            } else if (keyCode == e.VK_DOWN) {
                if (y >= 230) {
                    y = 230;
                } else {
                    y += 5;
                }
            }
        }

    }

    public Game() {

        //load up image
        ImageIcon i = new ImageIcon("image.png");
        image = i.getImage();

        //set up properties
        addKeyListener(new AL());
        setTitle("Game");
        setSize(250, 250);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBackground(Color.CYAN);
        setVisible(true);

    }

    public void paint(Graphics g) {
        dbimage = createImage(getWidth(), getHeight());
        dbg = dbimage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbimage, 0, 0, this);
    }

    public void paintComponent(Graphics g) {
        g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 30));
        g.setColor(Color.MAGENTA);
        g.drawString("Hello World!", 50, 50);
        g.setColor(Color.RED); 
        g.drawImage(image, 100, 100, this);
        repaint();
    }

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

}

最佳答案

上面的代码存在重大问题...

首先,如果您的图像与类文件一起存在,那么不要将其作为文件获取,而是将其作为资源获取,如 MadProg 所示(并且本网站上的大多数类似问题都会告诉您):

    // get your image as a resource
    URL resource = Game.class.getResource(RESOURCE_PATH);
    BufferedImage img = null;
    try {
        // read in using ImageIO
        img = ImageIO.read(resource);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }

接下来,永远不要直接在 JFrame 中绘制,当然也不要在其 Paint 方法中绘制。相反,请查看 Swing 绘图教程并遵循他们的指导:在 JPanel 的 PaintComponent 方法中进行绘制,但只有在调用 super 的 PaintComponent 方法之后,以便绘制可以沿着绘制链继续进行。:

// draw within the paintComponent method, not the paint method
@Override
protected void paintComponent(Graphics g) {
    // call the super's method to all painting to chain down the line
    super.paintComponent(g);
    if (dbimage != null) {
        g.drawImage(dbimage, imgX, imgY, this);
    }
}

在修复 GUI 的大小时,我更喜欢覆盖 JPanel 的 getPreferredSize,例如:

// set the preferred size of the main Game JPanel safely 
@Override
public Dimension getPreferredSize() {
    if (isPreferredSizeSet()) {
        return super.getPreferredSize();
    }
    return new Dimension(PREF_W, PREF_H);
}

把所有的东西放在一起,像这样可能工作:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Game extends JPanel {
    public static final String RESOURCE_PATH = "image.png";
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private BufferedImage dbimage = null;
    private int imgX = 0;
    private int imgY = 0;

    public Game(BufferedImage dbimage) {
        this.dbimage = dbimage;
    }

    // draw within the paintComponent method, not the paint method
    @Override
    protected void paintComponent(Graphics g) {
        // call the super's method to all painting to chain down the line
        super.paintComponent(g);
        if (dbimage != null) {
            g.drawImage(dbimage, imgX, imgY, this);
        }
    }

    // set the preferred size of the main Game JPanel safely 
    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        // get your image as a resource
        URL resource = Game.class.getResource(RESOURCE_PATH);
        BufferedImage img = null;
        try {
            // read in using ImageIO
            img = ImageIO.read(resource);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        // pass image into your Game JPanel
        Game mainPanel = new Game(img);

        // pass the JPanel into a JFrame
        JFrame frame = new JFrame("Game");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);  // and display it
    }

    public static void main(String[] args) {
        // start your Swing GUI in a thread-safe manner
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}

接下来查找键绑定(bind)以帮助您使用此 GUI 通过击键制作动画

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

相关文章:

php - 通过 PHP 使用 MySQL 数据库表中的值生成 SVG 图形

java - 从旋转位图Android获取像素

java - tomcat - solaris getRequestURI() 返回部分解码的 uri

Java图像显示

java - 如何在忽略转义逗号的同时拆分逗号分隔的字符串?

java - 如何设置gridlayout jpanel的大小

java - 将数组添加到对象

math - 为什么通过添加坐标来添加两个点是错误的?

java - 如何在 Vaadin Binder 中确认验证

java - Android[Java]-如何实例化特定的Bundle对象