我正在寫一個小型的自上而下的遊戲,玩家在箭頭鍵控制的二維數組中移動。
我一定看過每一個關於鍵綁定的教程,但是我無法讓我的鍵綁定更新主'樓層'對象。幫幫我!對不起,文本牆,但我認爲這三個文件的上下文是有幫助的。謝謝!爪哇鑰匙綁定和箭頭鍵
編輯:SSCCE
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package palace.hero;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SSCCE
{
public static void main(String[] args)
{
JPanel gridPanel = new JPanel();
int xCoord = 0;
int yCoord = 0;
//Key Bindings
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
gridPanel.getActionMap().put("up", new SSCCEKA(xCoord, yCoord, "up"));
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
gridPanel.getActionMap().put("down", new SSCCEKA(xCoord, yCoord, "down"));
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
gridPanel.getActionMap().put("left", new SSCCEKA(xCoord, yCoord, "left"));
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
gridPanel.getActionMap().put("right", new SSCCEKA(xCoord, yCoord, "right"));
//Window
JFrame window = new JFrame("Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int windowHeight = 1125;
int windowWidth = 900;
window.setPreferredSize(new Dimension(windowHeight, windowWidth));
window.add(gridPanel);
window.pack();
window.setVisible(true);
gridPanel.requestFocusInWindow();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package palace.hero;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SSCCEKA extends AbstractAction
{
String direction;
int x = 0;
int y = 0;
public SSCCEKA(int x, int y, String direction)
{
this.x = x;
this.y = y;
}
@Override
public void actionPerformed(ActionEvent ae)
{
if(direction.toLowerCase().equals("up"))
{
x++;
}
if(direction.toLowerCase().equals("down"))
{
x--;
}
if(direction.toLowerCase().equals("left"))
{
y--;
}
if(direction.toLowerCase().equals("right"))
{
y++;
}
}
}
是否檢測不到按鍵或其他問題? (如果是這樣,構建一個[SSCCE](http://sscce.org)應該是微不足道的。) – aioobe
不,它們被檢測到,我只是不知道如何給AbstractAction的'actionPreformed'函數副作用。 (我已經將它用於打印「向上,向下,向左,向右」,但是我希望它實際上改變了主要類中的地板對象......) – Haskelier
如果你能解決你的問題會很有幫助...請參閱[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve) – Chrismas007