我正在开发 Yahtzee 游戏,但在加载骰子图像时遇到问题。我将 NetBeans 与 JFrame 组件结合使用,但希望直接在类中处理该文件,因为掷骰子时图像需要更改。
这是我的代码...不起作用...`
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() 方法,而且我不知道是什么。我已经在其他程序中成功使用了文件图像,但无法让这个程序工作!任何帮助将不胜感激!
最佳答案
不确定这是否是问题所在,但您应该从嵌入资源的 URL 路径读取图像
image = ImageIO.read(Die.class.getResource("dice.png"));
请注意,路径中不需要 src
。运行下面的代码,看看它是否适合您。它对我来说效果很好(考虑到路径变化)
顺便说一句,我在您的代码中没有收到有关 toString
的错误。并在 catch
block 中使用诸如 ex.printStackTrace()
之类的描述性内容,这样您就可以在抛出异常时看到实际的异常是什么。哦,在 drawImage
中使用 JPanel
和 ImageObserver
、this
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);
}
});
}
}
关于java - 从文件设置 JPanel 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213279/