从文件设置JPanel图像

时间:2014-01-19 04:38:21

标签: java swing jpanel

我正在进行一场Yahtzee游戏,并且无法为我的骰子加载骰子图像。我正在使用带有JFrame组件的NetBeans,但是我想直接在我的类中处理该文件,因为图像在滚动时需要更改。

这是我的代码......不起作用......`

public class Die extends JPanel {

    //current number of die.  Starts with 1.
    private int number;
    //boolean showing whether user wants to roll this die
    private boolean userSelectToRoll;
    private Random generate;
    private boolean rolled;
    private Graphics2D g;
    private BufferedImage image;


    public Die() {
        this.userSelectToRoll = true;
        this.generate = new Random();
        this.rolled = false;
        try{
            image = ImageIO.read(new File("src/dice1.png"));
        }catch (IOException ex){
     //       System.out.println("Dice picture error");
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawImage(image, 0, 0, null);
    }
}`

我也尝试使用jLabel图标,但它也没有用。当我尝试调试它时,我收到一条错误消息:

non-static method tostring() cannot be referenced from a static context

但我不明白,因为我没有调用toString()方法,我无法弄清楚是什么。我已经在其他程序中成功使用了文件图像,但是无法使用这个图像!任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

不确定这是否是问题,但您应该从嵌入资源的URL路径中读取图像

image = ImageIO.read(Die.class.getResource("dice.png"));

请注意我在路径中不需要src。运行以下代码,看看它是否适合您。它对我来说很好(给定路径改变)

顺便说一句,我没有收到关于代码的toString的错误。并在ex.printStackTrace()块中使用catch等描述性内容,以便您可以看到抛出实际异常的内容。哦,使用JPanel中的ImageObserverthisdrawImage

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class Die extends JPanel {

//current number of die.  Starts with 1.
    private int number;
//boolean showing whether user wants to roll this die
    private boolean userSelectToRoll;
    private Random generate;
    private boolean rolled;
    private Graphics2D g;
    private BufferedImage image;

    public Die() {
        this.userSelectToRoll = true;
        this.generate = new Random();
        this.rolled = false;
        try {
            image = ImageIO.read(Die.class.getResource("stackoverflow5.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawImage(image, 0, 0, this);
    }

    public Dimension getPreferredSize() {
        return new Dimension(400, 400);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new Die());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}