Muhammad Sarib
Muhammad Sarib

Reputation: 459

How to properly use keylistener in java

I am trying to move the character in this game forward and backwards with left and right keys using KeyListner but I can't seem to move the character a bit. I looked at this answers with no luck:

How to use keyListener properly in Java and How do i use KeyListener in java?

Here is my code:

package test2;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Test
{
    public static void main(String[] args)
    {
        Frame A1 = new Frame();
    }

}

class Frame
{
    JFrame window;

    public Frame ()
    {
        awt();
    }

    public void awt()
    {
        Design A2 = new Design()
        {
            @Override
            public void keyTyped(KeyEvent e)
            {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void keyPressed(KeyEvent e)
            {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void keyReleased(KeyEvent e)
            {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        };

        window = new JFrame("Kyo's test");

        window.setVisible(true);
        window.setSize(1280, 786);
        window.add(A2);

        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


abstract class Design extends JPanel implements ActionListener, KeyListener
{
    // Timer objects for character and saws
    Timer movementOfCharacter = new Timer(5, this);
    Timer movementOfSaw = new Timer(15, this);

    // Variables for movement
    int xAxisOfCharacter = 50, velocityOfCharacter=2, yAxisOfSaw = 0, velocityOfSaw = 10;

    private Image tree, background, character, saw;


    // Constructor
    Design()
    {
        movementOfCharacter.start();

        addKeyListener(this);

        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }

    // Constructor of Graphics
    protected void paintComponent(Graphics graphics)
    {
        super.paintComponent(graphics);

        Graphics2D graphics2d = (Graphics2D) graphics;

        graphics2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        movementOfSaw.start();

        // Body for background
        {
            ImageIcon whale = new ImageIcon(this.getClass().getResource("whale.jpg"));
            background = whale.getImage();

            graphics2d.drawImage(background, 0, 0, getWidth(), getHeight(), this);
        }

        // Body for trees
        {
            ImageIcon environment = new ImageIcon(this.getClass().getResource("Tree_Alt.png"));
            tree = environment.getImage();

            graphics2d.drawImage(tree, getWidth()/8, getHeight()-217, this);
            graphics2d.drawImage(tree, (getWidth()/5)*2, getHeight()-217, this);
            graphics2d.drawImage(tree, (getWidth()/6)*4, getHeight()-217, this);
        }

        // Body for Saws of death
        {
            ImageIcon sawOfDeath = new ImageIcon(this.getClass().getResource("saw.gif"));
            saw = sawOfDeath.getImage();

            // First saw
            {
                graphics2d.drawImage(saw, (getWidth()/11), yAxisOfSaw, 100, 100, this);
            }

            // Second saw
            {
                graphics2d.drawImage(saw, (getWidth()/7)*2, yAxisOfSaw, 100, 100, this);
            }

            // Thirf saw
            {
                graphics2d.drawImage(saw, (getWidth()/2)-10, yAxisOfSaw, 100, 100, this);
            }

            // Fourth saw
            {
                graphics2d.drawImage(saw, (getWidth()/6)*4, yAxisOfSaw, 100, 100, this);
            }

            // Fifth saw
            {
                graphics2d.drawImage(saw, (getWidth()/6)*5, yAxisOfSaw, 100, 100, this);
            }
        }

        // Body for exit
        {
            graphics.setColor(Color.red);
            graphics.fillRect(getWidth()-5, getHeight()-150, 5, 150);
        }

        // Body for Character
        {
            ImageIcon blanka = new ImageIcon(this.getClass().getResource("Blank.gif"));
            character = blanka.getImage();

            graphics2d.drawImage(character, xAxisOfCharacter, getHeight()-150, 150, 155, this);
        }
    }

    public void actionPerformed(ActionEvent e)
    {
        yAxisOfSaw += velocityOfSaw;

        if(yAxisOfSaw > 0 || yAxisOfSaw < getHeight()-100)
            velocityOfSaw = -velocityOfSaw;

        repaint();
    }

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

        if(key == KeyEvent.VK_LEFT)
        {
            velocityOfCharacter = -5;
        }
        if(key == KeyEvent.VK_RIGHT)
        {
            velocityOfCharacter = 5;
        }
    }

    public void keyTyped(KeyEvent e)
    {
    }

    public void keyReleased(KeyEvent e)
    {
    }
}

Could anyone please tell me where and what am I doing wrong here?

Upvotes: 3

Views: 276

Answers (1)

Bentaye
Bentaye

Reputation: 9766

The issue

When you do

Design A2 = new Design() {
    @Override
    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
     public void keyPressed(KeyEvent e) {
         throw new UnsupportedOperationException("Not supported yet."); 
    }

    @Override
    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
};

You are overwriting the code your wrote in your Design abstract class with just throwing exceptions.

Solutions

Your Design class does not have to be abstract as it does not have unimplemented methods. So I can see 2 ways to use the code you wrote in you Design class:

First way

Remove the abstract keyword so you can instantiate your Design class like a normal class with the new keyword. So declare the Design class this way:

class Design extends JPanel implements ActionListener, KeyListener

And then instantiate A2 this way:

Design A2 = new Design();

Second way

If, for some reason, you need the class to be abstract is to instantiate your A2 object this way:

Design A2 = new Design() {};

This will work and not overwrite any method you wrote in your Design class. But that makes little sense, the first way above makes more sense.

Notes

Note 1

Now if you add a printout in your Design.keyPressed you can see that it is called (you will see logs in your console):

public void keyPressed(KeyEvent e) {
    System.out.println("KeyEvent: "+e);
    int key = e.getKeyCode();
    ...

Note 2

Also looking at the keyPressed method, I think you also need to update the character X axis coordinate, so add this line after your if statements:

xAxisOfCharacter += velocityOfCharacter;

It should look like this:

public void keyPressed(KeyEvent e) {
    System.out.println("KeyEvent: "+e);
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_LEFT) {
        velocityOfCharacter = -5;
    }
    else if(key == KeyEvent.VK_RIGHT) {
        velocityOfCharacter = 5;
    }
    xAxisOfCharacter += velocityOfCharacter;
}

Upvotes: 1

Related Questions