【发布时间】:2017-05-14 18:09:53
【问题描述】:
一段时间以来,我一直在尝试向我的代码中添加一些关键输入,但由于某种原因,它不能在一个类中工作,但在另一个类中它工作得很好,我不知道为什么。这里的一个例子是有效的。
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);
}
}
但是,当我尝试将它放入我的 Sprite 类并得到相同的响应时,什么也没发生,我尝试更改顺序,每次我都没有得到响应,即使它们没有错误消息。该特定问题的代码在我的主要方法中如下
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);
如果您希望精灵类的其余部分帮助找出问题所在,可以在指向我的另一个问题的链接中找到整个问题。 Why can't I erase my Sprite
【问题讨论】:
标签: java input jframe sprite keystroke