2014-01-19 70 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