Java - Paint、JFrame 和背景
我正在尝试为我的游戏绘制欢迎屏幕,但仅限于游戏加载时。我不想在游戏过程中每次都重新绘制。
所以我这样做了(其中 isStart 被实例化为 true):
public myClass(String name){
setSize(800, 800);
setVisible(true);
setResizable(false);
runGame()
}
public void paint(Graphics g) {
if(nowStarting)
g.drawImage(WelcomeGameScreen, 0, 0, null);
isStart = false;
}
问题是图像会弹出一秒钟然后消失?奇怪的是,当我省略 if 语句/isStart 条件时它会起作用。这有什么问题吗?
I'm trying to paint a Welcome Screen for my game, but only when the game loads. I don't want it to repaint everytime during the game.
So I did this (where isStart is instantiated as true):
public myClass(String name){
setSize(800, 800);
setVisible(true);
setResizable(false);
runGame()
}
public void paint(Graphics g) {
if(nowStarting)
g.drawImage(WelcomeGameScreen, 0, 0, null);
isStart = false;
}
The problem is that the image will pop up for a second and then disappear? Oddly, it works when I leave out the if statement/isStart condition. What's wrong with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜测您没有逐字复制代码,并且上面的代码中有错误。如果你的代码是我认为的那样......
那么在开始时它会绘制你的启动屏幕。但是,因为您随后将 isStart 设置为 false,所以下次调用 Paint 时,将不再绘制图像。每当操作系统告诉屏幕需要刷新时(以及当您强制重新绘制时),都会调用paint方法。
解决这个问题的方法是,当游戏完成加载时,在应用程序中将 isStart 设置为 false,然后调用 repaint。
I am guessing that you have not copied verbatim the code, and there is an error in your code above. If your code is what I think it is...
Then at start it will draw your splash screen. But, because you are then setting isStart to false, the next time paint is called, the image will no longer be drawn. The paint method is called whenever the OS tells the screen that it needs to be refreshed (and when you force it with repaint).
The way you can get around this, is to set isStart to false in your application when the game has finished loading, and then call repaint.
我猜一旦绘制面板,您的
newStarting
布尔值就会更改为false
。I guess your
newStarting
boolean gets changed tofalse
as soon as the panel is painted.它立即消失的原因是 Swing 框架触发的重绘。另外,您已经在重写的 Paint() 方法中编写了欢迎屏幕的代码。
有关如何触发启动的详细说明,请参阅此链接窗户。
Java 1.6 中还有一个 SplashScreen 类
The reason it gets disappeared immediately is because of the repaints that are triggered by the Swing framework. Plus you have written the code for Welcome screen inside the overridden paint() method.
Refer this link for a detailed explanation of how to fire a splash window.
You also have a SplashScreen class in Java 1.6