如何在 Java 中渲染 2D 图像
我有一个关于 Java 的简单问题。如果这个问题真的很基本,我很抱歉,但我是一名初学者 Java 程序员:D
我想在窗口中渲染 2d 图像,但我无法弄清楚。我在这里查看了图形 API:
http ://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html
我能找到的唯一可行的方法是drawImage()。 不过,它对我不起作用,但也许它与 ImageObserver Observer 参数有关?我只是将 null 放在我在某处找到的一些教程之后,但我仍然收到编译错误: 这是我的绘制方法:
public void paint(Graphics g)
{
Image img1 = Toolkit.getDefaultToolkit().getImage("theImage.png");
g.drawImage(img1, 100, 100, null);
} // public void paint(Graphics g)
这是调用它的方法:
public static void main(String[] args)
{
MyGame game = new MyGame();
game.setVisible(true);
game.play();
} // public static void main(String[] args)
/** The play method is where the main game loop resides.
*/
public void play()
{
boolean playing = true;
//Graphics g = new Graphics();
while (playing)
{
paint();
}
} // public void play()
问题是当我在 while 循环中调用绘制时,我收到此错误: MyGame 中的 Paints(java.awt.Graphics) 无法应用于 ()
什么意思?我该如何修复它才能成功渲染 2d 图像?
预先感谢:D
I have a quick question about Java. I'm sorry if this question is really basic, but I'm a beginner Java programmer :D
I want to render a 2d image in a window, but I can't figure it out. I've looked at the graphics API here:
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html
and the only method I could find that might work is drawImage().
It wasn't working for me, though, but maybe it has to do with the ImageObserver Observer parameter? I just put null for that following some tutorial I found somewhere, but I still get a compile error:
Here is my paint method:
public void paint(Graphics g)
{
Image img1 = Toolkit.getDefaultToolkit().getImage("theImage.png");
g.drawImage(img1, 100, 100, null);
} // public void paint(Graphics g)
and here are the methods that call it:
public static void main(String[] args)
{
MyGame game = new MyGame();
game.setVisible(true);
game.play();
} // public static void main(String[] args)
/** The play method is where the main game loop resides.
*/
public void play()
{
boolean playing = true;
//Graphics g = new Graphics();
while (playing)
{
paint();
}
} // public void play()
The thing is when I call paint in the while loop, I get this error:
paints(java.awt.Graphics) in MyGame cannot be applied to ()
What does that mean? How can I fix it so I can successfully render a 2d image?
Thanks in advance :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
repaint(); 代替
paint();
Instead of
paint();
userepaint();
您应该覆盖
paintComponent(图形g)
。另外,正如 @TotalFrickinRockstarFromMars 建议的,您应该调用repaint()
。You should be overriding
paintComponent(Graphics g)
. Also, as @TotalFrickinRockstarFromMars suggested, you should be invokingrepaint()
.class Game extends JComponent { // 你的游戏类
private Image getImage(String imageUrl) {
}
PaintComponent(Graphics g) {
}
}
class Game extends JComponent { // Your game class
private Image getImage(String imageUrl) {
}
paintComponent(Graphics g) {
}
}