I am trying out something new and I am wondering if this is valid and is not working because of some other code glitch.
Graphics class:
import java.awt.*;
import javax.swing.JPanel;
public class Drawing extends JPanel{
KeyCommands kc = new KeyCommands ();
public void startGraphics (){
System.out.println ("Adding KeyListener");
addKeyListener (kc);
System.out.println ("Taking Focus");
requestFocus();
repaint();
}
public void paintComponent (Graphics g){
super.paintComponents(g);
g.fillRect(15,40, 40, 40);
}
}
KeyListener portion
import java.awt.event.*;
public class KeyCommands implements KeyListener{
CharacterAnimation charAnimate = new CharacterAnimation ();
Frame frame;
String direction;
public void setUpWindow(Frame f){
frame = f;
System.out.println ("Frame Set up");
}
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
System.out.println ("Key Pressed");
if (key == KeyEvent.VK_UP){
direction = "UP";
}
else if (key == KeyEvent.VK_DOWN){
direction = "DOWN";
}
else if (key == KeyEvent.VK_LEFT){
direction = "LEFT";
}
else if (key == KeyEvent.VK_RIGHT){
direction = "RIGHT";
}
else if (key == KeyEvent.VK_ESCAPE){
System.out.println ("Escape Pressed");
frame.closeWindow();
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
I am trying to separate the KeyListener from the drawing class. Then I want to add the KeyListener class to the drawing class, so they act like one code, but they are separate. I am assuming that when I add it and the drawing class has focus and I press a button it will realize that it is a key event and then go to the KeyCommands class to see what it needs to do. I ran into this problem when I tried closing the window with escape. That is why only that one like has a println.
Thanks for any help.