How do I call Graphics Method inside KeyListener?

2019-03-01 02:57发布

问题:

Ahead of time, I would like to say there have been many posts similar to this, however, none of them apply to me or none of them actually have any answer at all, and are outdated, meaning there could be new java features that could help me solve my problem.

Anyway, I wanted to make a game where there is tennis rackets. Of course, they would have to rotate. In order to rotate, I must call my Graphics2D method inside my KeyListener. How would I do this WITHOUT adding a new Graphics2D variable inside my key listener method?

Here is all the methods I have that involve accomplishing this goal:

        public void draw(Graphics2D g2d) {
            g2d.drawImage(getPaddleImg(), x, y, null);
        }

        public static Image getPaddleImg() {
            ImageIcon ic = new ImageIcon("C:/Users/Elliot/Desktop/Eclipse Game Tennis/paddle.png");
            return ic.getImage();
        }

        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            if(key==KeyEvent.VK_W){
                g2d.rotate(Math.toRadians(5));
            } else if(key==KeyEvent.VK_W) {
                g2d.rotate(Math.toRadians(-5));
            }

        public void keyReleased(KeyEvent e) {
            int key = e.getKeyCode();

            if(key==KeyEvent.VK_W){
                g2d.rotate(Math.toRadians(0));
            } else if(key==KeyEvent.VK_W) {
                g2d.rotate(Math.toRadians(0));
            }
        }

I know, this code would give me an error because of the g2d inside of the KeyPressed() and KeyReleased() method. How would I call the g2d inside these two methods? Or how would I do the same thing inside the draw() method?

回答1:

The wrong way: You can use Component.getGraphics() to get the graphics object.

The right way: All painting should be done inside the paint(Component) method. This is because a user could resize/open/close the window at any time. In your KeyListener (also research keybindings) you should update a setting on how the player/ racket should be drawn, and then call repaint()



回答2:

OK! I actually figured it out by myself! What I did is called the g2d.rotate(.....) inside my draw() method. What I did is created variables that check for rotation, and set them true or false inside of my KeyPressed() method. Here is the code I used inside the draw() method:

 if(isRotatingPositive == true) {
    g2d.rotate(Math.toRadians(speed));
 } else if(isRotatingNegative == true) {
    g2d.rotate(Math.toRadians(-speed));
 }