[英]How to detect keyboard input?
I am trying to make a square in a JFrame
to move around the frame by detecting keyboard input. 我试图在
JFrame
中建立一个正方形,以通过检测键盘输入来在框架中移动。 I tried looking on the internet and that is where I got the keyPressed()
method from. 我尝试在Internet上查找,这就是我从中获取
keyPressed()
方法的地方。 What I am looking for is how to declare it in the main()
method so it will actually update x and y. 我正在寻找的是如何在
main()
方法中声明它,以便它实际上将更新x和y。 Please try to keep it as simple as possible. 请尝试使其尽可能简单。
public class Game1{
public static int x = 1;
public static int y = 1;
static GraphicsClass graphics = new GraphicsClass();
static JFrame frame = new JFrame("Test");
public static void main(String[] args){
frameInit();
while(true){
//The problematic line, how do I declare it:
keyPressed();
frame.add(BorderLayout.CENTER, graphics);
frame.repaint();
}
}
public static void keyPressed(KeyEvent i){
int e = i.getKeyCode();
while(e == KeyEvent.VK_UP){
y--;
}
while(e == KeyEvent.VK_DOWN){
y++;
}
while(e == KeyEvent.VK_RIGHT){
y++;
}
while(e == KeyEvent.VK_LEFT){
x--;
}
}
public static void frameInit(){
frame.setSize(500, 500);
frame.setVisible(true);
frame.setResizable(false);
}
}
You should implements keyListener interface. 您应该实现keyListener接口。 Try this..
尝试这个..
public class Game1 extends JFrame implements KeyListener{ 公共类Game1扩展JFrame实现KeyListener {
public static int x = 1; public static int x = 1;
public static int y = 1; 公共静态整数y = 1;
static GraphicsClass graphics = new GraphicsClass(); 静态GraphicsClass图形= new GraphicsClass();
static JFrame frame = new JFrame("Test"); 静态JFrame frame = new JFrame(“ Test”);
public static void main(String[] args){ 公共静态void main(String [] args){
frameInit();
while(true){
//The problematic line, how do I declare it:
keyPressed();
frame.add(BorderLayout.CENTER, graphics);
frame.repaint();
}
} }
If you want to keep this as simple as possible you should create your Swing-Application by using Netbeans. 如果您想使其尽可能简单,则应使用Netbeans创建Swing应用程序。 It has a nice Form-Designer built in where you can add a KeyListener just with a click.
它内置了一个不错的Form-Designer,您可以在其中单击即可添加KeyListener。 You don't even have to care about a main-method which is also generated.
您甚至不必关心也会生成的主方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.