gpt4 book ai didi

java - 我如何通过按键连续移动到 ActionMap 中?

转载 作者:行者123 更新时间:2023-12-02 05:08:48 24 4
gpt4 key购买 nike

我的代码有问题。我尝试做蛇游戏,但我停在了绘制面板的 Action map 的连续移动上。我尝试在循环中使用drawPanel.repaint,但它仅在到达末尾时向我显示,但我希望所有运动都在ActionMap中给出。我怎样才能做到呢?或者有人有其他解决方案吗?

    DrawPanel drawPanel = new DrawPanel();

public Snake(){
InputMap inputMap = drawPanel.getInputMap();//JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = drawPanel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
actionMap.put("rightAction", rightAction);
inputMap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
actionMap.put("leftAction", leftAction);
inputMap.put(KeyStroke.getKeyStroke("UP"), "upAction");
actionMap.put("upAction", upAction);
inputMap.put(KeyStroke.getKeyStroke("DOWN"), "downAction");
actionMap.put("downAction", downAction);

add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}

private class DrawPanel extends JPanel {

protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.GREEN);
g.fillRect(x, y, 10, 10);
}
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}

Action downAction = new AbstractAction(){
public void actionPerformed(ActionEvent e) {
while (y<390)
{
y +=+10;
drawPanel.repaint();
}
/* if (y<390)
y +=+10;
else
y = 390;
drawPanel.repaint();
*/
}
};

Action upAction = new AbstractAction(){
public void actionPerformed(ActionEvent e) {
if (y>0)
y -=10;
else
y = 0;
drawPanel.repaint();
}
};

Action leftAction = new AbstractAction(){
public void actionPerformed(ActionEvent e) {
if (x>0)
x -=10;
else
x = 0;
drawPanel.repaint();
}
};

Action rightAction = new AbstractAction(){
public void actionPerformed(ActionEvent e) {
if (x<390)
x +=10;
else
x = 390;
drawPanel.repaint();
}
};

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Snake();
}
});
}
}

最佳答案

如图herehere ,您可以在 javax.swing.TimerActionListener 中调用您自己的 Action 实例的 actionPerformed() 方法。 。您可以调整计时器的延迟来调节动画的节奏。

关于java - 我如何通过按键连续移动到 ActionMap 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27523920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com