2014-01-19 47 views
0

我正在制作Yahtzee游戏,并且无法为我的骰子加载一个骰子图像。我正在使用带有JFrame组件的NetBeans,但希望直接在我的课程中处理该文件,因为图片在滚动时需要更改。设置来自文件的JPanel图像

这里是我的代码...不行...`

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()方法,我无法弄清楚什么是。我已经在其他程序中成功使用过文件图像,但无法让这个文件工作!任何帮助,将不胜感激!

回答

2

不知道这是一个问题,但你应该从URL读取路径图像嵌入式资源

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

通知我都不怎么需要src路径。运行下面的代码,看看它是否适合你。它适用于我(鉴于路径变化)

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

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); 
      } 
     }); 
    } 
} 
+0

谢谢!这工作!我是新手,所以只是尝试新事物。 – user3211411