我一直在嘗試添加一些關鍵輸入到我的代碼一段時間,但由於某種原因,它不會在一個類中工作,但在另一個它工作得很好,我不知道爲什麼。一個例子這是一個工作。爲什麼我的Java密鑰輸入有時只能工作?
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);
如果你想在精靈類的其餘部分,以幫助找出問題是什麼,整個事情可以在鏈接到我的其他問題被發現。
嗯,這有點幫助,但我希望能在我的Sprite類的主要方法註冊按鍵,有沒有什麼辦法,我可以做到這一點? –
鍵綁定需要註冊在屏幕上/將在屏幕上活動的組件 – MadProgrammer
那麼,我的代碼稍微改變了一點,謝謝! :) –