私はコードにいくつかのキー入力をしばらく追加しようとしていましたが、何らかの理由で1つのクラスでは動作しませんが、他のクラスではうまく動作しています。ここに例があります。私はSpriteクラスにそれを置くと同じ応答を取得しようとしたとき私の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);
}
}
は、しかし、何も私は順序を変更しようとしたと私はやるたびにエラーメッセージが自分でなくても応答を得ることはありませ起こりませんでした。あなたはスプライトクラスの残りの部分は問題は全体の事は私の他の質問へのリンクで見つけることができているかを把握手助けしたい場合は、その特定の問題のコードは私の主な方法
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
これは、私のコードを少し変更しました。 :) –