所以我试图编写一些允许我设置自定义键的代码,而我似乎无法解决静态引用的非静态问题。
代码:
import javax.swing.JFrame;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
public class keyTester extends JFrame
{
public keyTester()
{
this.addKeyListener(new keyListener());
this.setSize(400, 400);
this.setVisible(true);
}
private class keyListener implements KeyListener
{
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == Field.set(KeyEvent.getClass().getField("VK_LEFT"), int.class));
System.out.println("Left");
if (key == KeyEvent.VK_RIGHT)
System.out.println("Right");
if (key == KeyEvent.VK_UP)
System.out.println("Up");
if (key == KeyEvent.VK_DOWN)
System.out.println("Down");
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
}
错误:
C:\Users\Matt\Dropbox\My Projects\Tron\keyTester.java:21: error: non- static method getClass() cannot be referenced from a static context
if (key == Field.set(KeyEvent.getClass().getField("VK_LEFT"), int.class));
^
C:\Users\Matt\Dropbox\My Projects\Tron\keyTester.java:21: error: non-static method set(Object,Object) cannot be referenced from a static context
if (key == Field.set(KeyEvent.getClass().getField("VK_LEFT"), int.class));
^
C:\Users\Matt\Dropbox\My Projects\Tron\keyTester.java:21: error: 'void' type not allowed here
if (key == Field.set(KeyEvent.getClass().getField("VK_LEFT"), int.class));
^
3 errors
Tool completed with exit code 1
是否有任何解决方案可以访问VK_LEFT变量而无需通过此方法或以任何方式解决此问题?