正如您已经知道的那样,我开始编写有关太空的小游戏。
“不错的开始”- https://stackoverflow.com/questions/19818655/simulation-of-spaceplanets-and-stars :D
我写了一个工作的小计划,第一点是“随机生成星星”。 你可以说,使用随机更容易。
Random random = new Random();
int x = random.nextInt(getWidth()*2);
int y = random.nextInt(getHeight()*2);
g.drawImage(Image,x,y,4,4,this);
但是它不起作用(
它不起作用,因为图片在屏幕上“跳跃”。
关于视频:https://www.youtube.com/watch?v=EELo_-eh3fA
那么如何随机带来星星呢? (星星是小图片或白色方 block ) 这就是全部代码:
import java.awt.Graphics;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import java.io.IOException;
public class Game extends JComponent {
public Game() {
try {
image = ImageIO.read(getClass().getResource("star.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
repaint();
Random random = new Random();
int x = random.nextInt(getWidth()*2);
int y = random.nextInt(getHeight()*2);
g.drawImage(Image,x,y,4,4,this);
}
public static void main(String[] args) {
JFrame frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.add(new Game());
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.addMouseListener(mos);
frame.addMouseMotionListener(mos);
}
}
这里的代码不起作用( 图片再次跳跃。
public void paintComponent(Graphics g) {
super.paintComponent(g);
repaint();
Random random = new Random();
int x = random.nextInt(getWidth()*2);
int y = random.nextInt(getHeight()*2);
g.drawImage(kor,x,y,10,10,this);
}
@camickr,你说要删除 repaint();但没有它我就看不到照片
最佳答案
- 自定义绘制是通过重写
paintComponent()
方法而不是 Paint() 方法来完成的。 - 切勿在绘画方法中调用 repaint()。这将导致无限循环。
How to fix the picture? that they did not jump.
基本上需要在绘画方法之外确定位置。
也许你可以从 Custom Painting Approaches 开始获得在面板上绘制多个对象的想法。我建议使用第一种方法将对象添加到列表中。因此,您可以将多个对象添加到列表中,但每个对象都会被赋予一个随机位置。
You said to remove repaint(); but without it I do not get a picture
您是否花时间查看我给您的链接?这些示例向您展示了何时执行 repaint()。
关于java - 在屏幕上随机显示图像(JFrame),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19819456/