mr_lou
mr_lou

Reputation: 1920

Have system not call keyPressed in my class that extends class that implements KeyListener

Let's say I have a class MyKeyListener that implements java.awt.event.KeyListener, meaning it has a method:

public void keyPressed(java.awt.event.KeyEvent keyEvent) {}

Now I want to maky myself another class MyFrameworkClass that extends MyKeyListener but kinda overrides the keyPressed() method.

public void keyPressed(int keyCode) {}

Obviously this won't work, since the system calls keyPressed with a java.awt.event.KeyEvent object, but I'm now asking for an int.

If my keyPressed(int keyCode) was renaned to e.g. myKeyPressed(int keyCode), then my problem would be solved. Then I could do something like this in MyKeyListener class:

public void keyPressed(java.awt.event.KeyEvent keyEvent) {
 myKeyPressed(keyEvent.getKeyCode());
}

public void abstract myKeyPressed(int keyCode);

My question: Is there any way I can do that while keeping the same name for both methods? Meaning, have the system call the keyPressed() in class MyKeyListener rather than the one in MyFrameworkClass despite the fact that I'm extending MyKeyListener (because I want to manually call the one in MyFrameworkClass from MyKeyListener.

Upvotes: 0

Views: 62

Answers (1)

folkol
folkol

Reputation: 4883

You are right on track there. Two methods with separate signatures (In your case, parameter list) are treated as different methods.

You could implement your idea like this:

package test;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class MyFramework {
    static class MyKeyListener implements KeyListener {
        @Override
        public void keyPressed(KeyEvent e) {
            keyPressed(e.getKeyCode());
        }
        public void keyPressed(int keyCode) {}

        @Override public void keyTyped(KeyEvent e) { }
        @Override public void keyReleased(KeyEvent e) { }
    }

    static class MyFrameworkClass extends MyKeyListener {
        @Override
        public void keyPressed(int keyCode) {
            System.out.println(String.format("Key pressed: '%d'", keyCode));
        }
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame("Framework test");
        jFrame.setSize(200, 200);
        jFrame.addKeyListener(new MyFrameworkClass());
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }
}

Upvotes: 1

Related Questions