I've been trying to add some key input to my code for a while now, but for some reason it won't work in one class but in another it works just fine and I don't know why. An Example Here Is the one that DOES work.
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
public class KeyStrokeSample {
public static void main(String[] a) {
String ACTION_KEY = "theAction";
JFrame frame = new JFrame("KeyStroke Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton buttonA = new JButton("Press 'W'");
Action actionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
JButton source = (JButton) actionEvent.getSource();
System.out.println(source.getText());
}
};
KeyStroke W = KeyStroke.getKeyStroke("W");
InputMap inputMap = buttonA.getInputMap();
inputMap.put(W, ACTION_KEY);
ActionMap actionMap = buttonA.getActionMap();
actionMap.put(ACTION_KEY, actionListener);
frame.add(buttonA);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
However when I tried to put it into my Sprite class and get the same response NOTHING HAPPENED I've tried changing the order and every time I don't get a response even though their is no error message. The code for that particular problem is below in my main method
public static void main(String[] args) throws IOException,
InterruptedException{
//setting the window and sprites
Sprite orig_world = new Sprite(ImageIO.read(new
File("C:/Users/sfiel42/Documents/game/castles.png")),0,0);
Sprite world = new Sprite(ImageIO.read(new
File("C:/Users/sfiel42/Documents/game/castles.png")),0,0);
JLabel label = new JLabel();
label.setLocation(0,0);
label.setIcon(new ImageIcon(world.getSprite()));
label.setVisible(true);
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(783,615);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
Sprite archer = new Sprite(ImageIO.read(new
File("C:/Users/sfiel42/Documents/game/archer.png")),30,40);
String ACTION_KEY = "theAction";
JButton buttonA = new JButton("Button For W");
Action actionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
JButton source = (JButton) actionEvent.getSource();
System.out.println(source.getText());
}
};
KeyStroke W = KeyStroke.getKeyStroke("W");
InputMap inputMap = buttonA.getInputMap();
inputMap.put(W, ACTION_KEY);
ActionMap actionMap = buttonA.getActionMap();
actionMap.put(ACTION_KEY, actionListener);
buttonA.setVisible(false);
frame.add(buttonA);
If you want the rest of the sprite class to help figure out what the problem is the whole thing can be found at the link to my other question. Why can't I erase my Sprite