I'm working on a really simple project in Java to try to understand how to use KeyListener. I've created a Main class and a KeyListener, MouseListener class. I want to get something to happen when I press a keyboard key. So far the only thing that is working is "Hello" when I click.
Here is my code:
import javax.swing.JFrame;
import javax.swing.JPanel;
public class KeyPractice{
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.addKeyListener(new KeyEar());
panel.addMouseListener(new KeyEar());
frame.add(panel);
frame.setVisible(true);
frame.setSize(400, 400);
}
}
And the Keylistener class....
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class KeyEar implements KeyListener, MouseListener {
public KeyEar(){
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("Hello");
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0) {
System.out.println("Hello");
}
@Override
public void keyReleased(KeyEvent arg0) {
System.out.println("Hello");
}
@Override
public void keyTyped(KeyEvent arg0) {
System.out.println("Hello");
}
}