0
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

public class spriteStore {
public static BufferedImage playerStanding;

public void getImage()
{
    try
    {
        playerStanding = ImageIO.read(new File("Cobalt\\pictures\\playerStanding1.png"));
    }
    catch(Exception e){System.out.println("Picture not found");}
}
}

我正在尝试读取图像以保存为 BufferedImage 对象,但是当我运行主代码时,

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Cobalt {
public Boolean movingLeft, movingRight, firstJump, secondJump;
public int jump = 0;
public Dimension screenSize;
public JFrame frame;
public JPanel panel;

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run(){
            new Cobalt();
        }
    });

}
public Cobalt()
{
    frame = new JFrame("COBALT");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setResizable(true);
    frame.setSize(500,500); //width and height
    panel = new MyPanel();
    frame.getContentPane().add(panel);
}
class MyPanel extends JPanel
{

    private static final long serialVersionUID = 1L;

    public void paint(Graphics g)
    {
        Graphics g2D = (Graphics2D) g;
        super.paint(g);
        g2D.drawImage(spriteStore.playerStanding, 100, 100, null);
    }
}
}

并且图像不会显示。我正在使用 eclipse,并且相对来说是个菜鸟,所以请告诉我我的错误。

4

3 回答 3

0

我假设您的项目中有这样的结构:

Cobalt
|
\---src
    |   Cobalt.java
    |               
    \---pictures
            playerStanding1.png

尝试以下操作:

public static void main(String[] args) throws Exception {

    URL url = ClassLoader.getSystemClassLoader().
            getResource("pictures/playerStanding1.png");

    BufferedImage playerStanding = ImageIO.read(url);

    JLabel label = new JLabel(new ImageIcon(playerStanding));
    JOptionPane.showMessageDialog(null, label);

}
于 2013-06-05T04:15:34.763 回答
0

无需进行自定义绘画即可显示图像。

您可以使用 JLabel。阅读 Swing 教程中关于如何使用图标的部分。

于 2013-06-05T04:04:19.207 回答
-1

试试这个来创建 jlabel

ImageIcon icon = createImageIcon("images/middle.gif",
                             "a pretty but meaningless splat"); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

并像这样加载图像

/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
                                       String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
    return new ImageIcon(imgURL, description);
} else {
    //System.err.println("Couldn't find file: " + path);
    return null;
}
}

如果你想从一个网址

URL PicURL = new URL("http://...");
ImageIcon imgThisImg = new ImageIcon(PicURL));
jLabel2.setIcon(imgThisImg);
于 2013-06-05T04:09:05.810 回答