0
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

 class plc extends JPanel{
	plc()
	{
		this.addKeyListener(new MyKeyBoardListner());
		System.out.println("key listner added");
		
	}
	
 public void paintComponent(Graphics g)
 {
 	
 	super.paintComponent(g);
 	g.drawRect(0,0,10,60);
 	g.fillRect(0,0,10,60);
 	
 }	
	
	private class MyKeyBoardListner extends KeyAdapter
	{
		public void keyPressed(KeyEvent ke)
		{
			System.out.println(ke.getKeyCode());
		}
		
		
		
		
		
	}
	
	}
public class plank {
    
    public static void main(String[] args) {
    	
    
    JFrame frame =new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800,600);
    frame.setVisible(true);
    plc pl=new plc();
    frame.add(pl);
    }
}

This doesnt work when i press a key the event is not executed.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by adams161
0

Does the Panel with the listener have the focus?
Is it capable of getting the focus? There is a method to call for this.

0

i sometimes do something like this:

this.addKeyListener(new KeyListener() {

public void keyPressed(KeyEvent e)
{
 
    }

   public void keyTyped(KeyEvent e) {;

    }



    public void keyReleased(KeyEvent e) {;

    }




}

);

I'm wondering if it should have made you implement any other key event methods other than keypressed. If it does require that maybe it didn't' force you because it didn't quite recognize your class as a key listener class. Just guessing but perhaps you need an implement added to your class. not sure on exact name of implement but something like implements keylistener

Mike

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.