简体   繁体   中英

Java Graphics how to draw image in keyPressed

I am learning something new and somewhat difficult in Java-which is graphics! Below I explain what the two classes do. My new obstacle right now is coming up with a way to draw a different image for (ie: a projectile like a laser) coming from the ball by only pressing Z.

The problem is if I write a method for example: "g.drawImage(laser,laser_dx,laser_dy,this) in the if statement that contains "KeyEvent.VK_Z", my keyPressed method all of sudden says "this method is not used locally". What are my approaches to solving such an obstacle?

What I've done so far is written a nested class inside the "GameBoard" class that contains all the keyboard events of my program.

       private class Adapter extends KeyAdapter
       {

                public void keyPressed(KeyEvent e)
            {
                int keyCode = e.getKeyCode();
                if(keyCode == KeyEvent.VK_RIGHT)
                {
                    ball_dx += ball_velocity;

                }
                if(keyCode == KeyEvent.VK_LEFT)
                {
                    ball_dx -= ball_velocity;
                }
                if(keyCode == KeyEvent.VK_Z){

                }

            }

        }

Here's the drawing graphics method in a separate class called "Gameboard": This class just draws the image of a green ball(which is a .png image) and it can move left and right with the arrow keys!

    public class GameBoard extends JPanel implements ActionListener
    {

        public void paintComponent(Graphics g)
            {

            super.paintComponent(g);

            g.drawImage(ball, ball_dx, ball_dy, this);

            Toolkit.getDefaultToolkit().sync();

        }

        public void actionPerformed(ActionEvent arg0) 
        {

            repaint();
        }

    }

You have to rethink the logic: the code that handles the key events and the code that draws everything should share a state so that

  • events set the state
  • drawings change according to the state

Just to make it simple and to give you the idea:

boolean isLaser = false;

public void keyPressed(KeyEvent e) {
  isLaser = true;
}

public void keyReleased(KeyEvent e) {
  isLaser = false;
}

public void paintComponent(Graphics g) {
  if (isLaser)
    // do something
}

Of course in a more complex environment you would have a more structured solution like

List<Entity> entities = new ArrayList<Entity>();

public void paintComponent(Graphics g) {
  for (Entity e : entities)
    e.draw(g);
}

public void keyPressed() {
  entities.add(new LaserEntity(...));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM