English 中文(简体)
简单 2D Java 游戏
原标题:Simple 2D Java Game

我试图创造一个 Java 游戏,在这个游戏中,球从屏幕的顶部随机下降, 我们需要用一个位于屏幕底部的捕捉器抓住球。

我有一个困难的 时间想清楚 如何真正把这个 引到我的JFrame。

我有一个课 我的捕手,球, 游戏空间 我想把这一切放在一起。

我要怎么把抓手画在屏幕上?

目前,我有一个游戏课 看起来像这个。

public class Game extends JFrame implements KeyListener {

GameScreen gameScreen;
Catcher playerOneCatcher;

public static void main (String[] args) {
    new Game();
}

public Game() {

    super("CATCH");
    setSize(640,480);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    setLocationRelativeTo(null);
    setResizable(false);
    addKeyListener(this);


    this.gameScreen = new GameScreen();
    this.playerOneCatcher = new Catcher(40, 10); 


}

我在我的Catcher课上试过这样...

public void paintComponent(Graphics g) {
    g.setColor(Color.BLUE);
    g.fillRect(positionX, positionY, this.width, this.height);
}

但是,它没有显示在我的屏幕上。

如有任何帮助,将不胜感激。

最佳回答

您需要在这里重新思考您的策略。 Swing 是一个组件框架, 大部分组件都用于建立用户界面。 这些组件对于游戏中通常需要的东西并不最优化。 您想要查看双重缓冲、 外观等。 下一步是在图形2D 类上读取( 或者完全放弃 Swing! )

然而,回答你的问题,如果Catcher是一个摇摆组件,你需要在“亲子”组件中加入它,例如:

this.add(playerOneCatcher);

此元素也属于 gameScreen , 但从您的片段看, 这个元素是什么并不明显。 我希望这有帮助 。

另外,请看看这个,看一些想法:2D Java Game。将图示移到已铺设的图像上方

问题回答
  1. Did you call super.paintComponent (g) ? That can cause a few bugs.
  2. Did you call invalidate () or repaint () to repaint the thing you are painting on? I hope you have a special JComponent, and you are not drawing on a JFrame. That is NOT good.




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签