I am not sure what is incorrect

前端 未结 2 1244
粉色の甜心
粉色の甜心 2021-01-24 14:25

I am creating a small Java Jpanel game in which I am supposed to have a rocket that moves up and down via arrows and fires via space.
The firing method should work like th

相关标签:
2条回答
  • 2021-01-24 14:50

    The problem was quite simply that I had forgotten to use == in my if(boolean) statements.

    0 讨论(0)
  • 2021-01-24 15:09

    For one, as soon as my code starts you can see a bullet flying across the screen.

    The paintComponent() method is for painting only. You can't control when Swing will determine a component needs to be repainted.

    So, for example:

    t.start();
    

    should NOT be in the painting method. As soon as the frame is made visible the panel will be painted and the Timer will be started.

    You application code should control when the Timer is started.

    Other issues:

    1. you should not be using static variables. The variable should simply be instances of your class.

    2. the paintStars() method should not generate random locations. Again. a painting method should only paint the current state of the class. So if you want to change the location of the stars you should have a method like randomizeStars(). In this method you would update an ArrayList of Point objects. Each Point instance would represent the location of a star. Then the paintStars() method would simply iterate through the ArrayList and paint each star.

    3. you should not be using a KeyListener. A KeyListener only works if a component has focus. You can't guarantee that your component will lose focus. Instead you should be using Key Bindings. Key bindings allow you to handle a KeyEvent even if the component doesn't have focus. See Motion Using the Keyboard for more information and a working example.

    you can only fire once until the other bullet disappears

    Your canFire variable should be a boolean variable so it only has true/false values. Again you have a method that sets the state. Your game logic will then check the state before firing the bullet again.

    if(y==-20) y=249;
    if(y==250)y=-20;
    

    Don't hardcode values. The number should be based on the size of your panel. So you use methods like getWidth() and getHeight() to determine the current size of the panel.

    0 讨论(0)
提交回复
热议问题