[英]Object won't appear on keypress in java swing
So I am trying to make a very simple game in Java using swing. 因此,我试图使用swing创建一个非常简单的Java游戏。 It's a space invaders type game and I have successfully coded in the spaceship that moves left and right with key presses.
这是一款太空侵略者类型的游戏,我已经成功地在按键中左右移动的飞船中进行了编码。 However I am having a lot of trouble getting the "shot" to show up.
但是,要显示“镜头”非常麻烦。
I am not looking to position it just yet, I really just want to create an object on keypress to make it work. 我暂时不打算定位它,我真的只是想在按键上创建一个对象来使其工作。 I am assuming since it is not initially in the "paint" method, that is why it is not appearing.
我假设因为它最初不在“ paint”方法中,所以它没有出现。 But I don't know how to make it show up!
但是我不知道如何显示它! Any ideas?
有任何想法吗?
For reference here is current code: 供参考的是当前代码:
public void keyPressed(KeyEvent e) {
if (KeyEvent.VK_RIGHT == e.getKeyCode()) {
moveRight();
}
if (KeyEvent.VK_LEFT == e.getKeyCode()) {
moveLeft();
}
if (KeyEvent.VK_SPACE == e.getKeyCode()) {
shoot();
}
}
public void shoot() {
Laser laser = new Laser(new Point(200, 200));
this.repaint();
}
public void moveLeft() {
if (player.getCentre().getX() <= 20) {
player.setX(20);
} else {
double movement = player.getCentre().getX();
movement -= 10;
player.setX(movement);
}
this.repaint();
}
@Override
public void paint(Graphics g) {
setBackground(Color.black);
super.paint(g);
player.draw(g);
}
I just want to make shoot() successfully create an object and have it show up in my panel! 我只想使shoot()成功创建一个对象,并将其显示在面板中!
Problems/Suggestions: 问题/建议:
paintComponent
method, and be sure to call the super's method within your override. paintComponent
方法,并确保在您的覆盖范围内调用super的方法。 protected void paintComponent(Graphics g)
override and not a public void paint(Graphics g)
override, should contain code to do this. protected void paintComponent(Graphics g)
替代而不是public void paint(Graphics g)
替代)应包含执行此操作的代码。 We're a bit limited in any advice that we can give since you've posted a code snippet, one that we can't compile or run. 自从您发布了一个代码片段以来,我们无法提供任何建议,但是我们无法编译或运行它。 If these suggestions don't lead you to an answer, then please create and post a small but simple complete program that illustrates your problem, an MCVE .
如果这些建议没有为您带来答案,请创建并发布一个小而简单的完整程序来说明您的问题,即MCVE 。 Please check the link for the details of this very useful tool.
请检查链接以获取此非常有用的工具的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.