user2176567
user2176567

Reputation: 13

No response from KeyListener

I'm trying to make an easy Java program, but I cannot get any inpute from it. Can anyone suggest a solution?

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

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


class KeyIns extends JFrame implements KeyListener {

 public void KeyIns(){
     addKeyListener(this); //==> this is why .... 
 }

@Override
public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
    System.out.println("1");
}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub
    System.out.println("2");
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub
    System.out.println("2");
}

}

public class Hello {
public static void main(String[] args){

    KeyIns inkey = new KeyIns(); 
    inkey.setSize(368, 300);
    inkey.setLocation(250, 250);
    inkey.setVisible(true);
    }
}

Upvotes: 1

Views: 137

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347214

KeyListener will only respond if the component it is registered to is both focusable and has focus.

The other problem is JFrame contains a bunch of other components on top of it, including the root pane and content pane. Registering a KeyListener to the frame is probably never going to achieve anything

A better solution would be to use the Key bindings API

A lot will matter based on what it is you are trying to achieve

Upvotes: 4

sol4me
sol4me

Reputation: 15698

The problem is you are never invoking the method

 public void KeyIns(){
     addKeyListener(this); //==> this is why .... 
 }

Either invoke the method KeyIns() or remove the word void (so that it becomes constructor) like this

 public KeyIns(){
     addKeyListener(this); //==> this is why .... 
 }

Upvotes: 1

Related Questions