gpt4 book ai didi

Java 键绑定(bind)在按键时输出到控制台

转载 作者:行者123 更新时间:2023-12-01 12:42:11 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,当按下箭头键时,它会在屏幕上移动一个矩形。目前,在 KeyListener 被证明不可靠且相当无用之后,我正在研究按键绑定(bind)。在尝试使矩形移动之前,我只是尝试按下向上​​箭头键触发 System.out.println("Up key Pressed!"),只是为了确保我的 KeyBindings实际上正在工作。问题是,他们不是。我正在关注this教程,与我想要实现的有点不同,但仍然应该教我如何使用键绑定(bind)。为什么 KeyBinding 不起作用?

代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class GamePanel extends JPanel implements Runnable{

boolean isRunning = true;
int count = 0;
Thread t;
static int rectX = 250;
static int rectY = 250;
Action upAction;
Action downAction;
Action leftAction;
Action rightAction;

public GamePanel()
{
upAction = new UpAction();
t = new Thread(this);
t.run();
/*downAction = new DownAction();
leftAction = new LeftAction();
rightAction = new RightAction();*/
this.getInputMap().put(KeyStroke.getKeyStroke("UP"), "upMotion");
this.getActionMap().put("upMotion",upAction);

}
public void run()
{
loop();
}
public void loop()
{
if(isRunning)
{
Thread t = Thread.currentThread();
try
{
t.sleep(5);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}

}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
count += 1;
g.drawString(Integer.toString(count), 10, 10);
g.drawRect(rectX, rectY, 50, 50);
loop();
}
static class UpAction extends AbstractAction
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Up key pressed!");
rectY++;
}
}
}

主要 JFrame 代码:

import javax.swing.*;

public class MainFrame{

JFrame frame = new JFrame("Space Invaders");
GamePanel gamepanel = new GamePanel();

public MainFrame()
{
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.add(gamepanel);
}
public static void main(String[] args)
{
new MainFrame();
}


}

最佳答案

整个问题是您的面板没有焦点,因此无法接收任何输入事件。关注this后答案,添加 2 行解决了问题:

public GamePanel() {
...
setFocusable(true); //add this anywhere in this constructor
}

public MainFrame() {
...
frame.add(gamepanel);
gamepanel.requestFocusInWindow();
//add this after adding the panel to your frame and making it visible
}

编辑:

此外,您的代码有几个错误:

  • 向上移动应该是 y-- ,因为左上角的坐标为 [0,0] 和 x轴向右移动且 y正在下降(与数学课不同)
  • 您不应该永远调用 Thread.sleep()里面paint()方法,因为该方法必须尽可能快。
  • 您正在使用thread.run()“启动”一个新线程,使用thread.start()相反,这实际上会启动一个新线程,而不是仅仅调用 run当前线程中的方法。
  • 更改 ifwhile在你的loop方法,同时删除 loop调用paint解决前面两个错误的方法。

这些并不是为了批评你(每个人都从某个时刻开始),而是为了帮助你。

关于Java 键绑定(bind)在按键时输出到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24993711/

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