How do i get a graphics object in Java?

后端 未结 2 1392
误落风尘
误落风尘 2021-01-23 15:40

Im making a basic space invaders game. I got all the resources from the LWJGL .zip file (Im not using LWJGL librarys to create my game, just got the pictures, etc. from it.) Any

相关标签:
2条回答
  • 2021-01-23 15:57

    You will need to store the location of the "bullet" somewhere, and then access that state within your paintComponent(Graphics g) method. Really, this should be factored out quite a bit. Make your Shot class look something like this:

    public class Shot {
        private Point location; // Could be Point2D or whatever class you need
    
        public Shot(Point initLocation) {
            this.location = initLocation;
        }
    
        // Add getter and setter for location
    
        public void draw(Graphics g) {
            // put your drawing code here, based on location
        }
     }
    

    Then in your key pressed method,

    public void keySPACE(){
        // Add a new shot to a list or variable somewhere
        // WARNING: You're getting into multithreading territory.
        // You may want to use a synchronized list.
        yourJPanelVar.repaint();
    }
    

    And you'll extend JPanel and override paintComponent.

    public class GameScreen extends JPanel {
        public paintComponent(Graphics g) {
            for (shot : yourListOfShots) {
                 shot.draw(g);
            }
            // And draw your ship and whatever else you need
        }
     }
    

    That's the basic idea. Hope it makes some sense now. You could move the Shot's drawing code elsewhere, I suppose, but for simplicity, I just stuck on the Shot class itself.

    I will note that what I have above is some pretty messy code. Look into the MVC pattern. It makes for much cleaner state abstraction (decouples the state from the display code).

    0 讨论(0)
  • 2021-01-23 16:07

    The idea is that the listeners should change the state of the game (i.e. create a bullet, or change the location of the bullet, or whatever), and then call repaint(). Then Swing will invoke the paintComponent(Graphics g) method, which will paint the updated game state using the Graphics passed as argument.

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