我正在写一个小型的自上而下的游戏,玩家在箭头键控制的二维数组中移动。
我一定看过每一个关于键绑定的教程,但是我无法让我的键绑定更新主'楼层'对象。帮帮我!对不起,文本墙,但我认为这三个文件的上下文是有帮助的。谢谢!爪哇钥匙绑定和箭头键
编辑: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