0

So I am trying to code something that would allow me to set a custom key and I cannot seem to get around the issue of non-static referenced from static.

Code:

    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) {}
        }
    }

Error:

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

Is there any solution in which I would be able to access the VK_LEFT variable without going through this or any way to fix this problem??

Matt N
  • 1
  • 2
  • Oops -- [A better duplicate question](http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static). Please search on your error first before posting. – Hovercraft Full Of Eels Jun 14 '16 at 02:12
  • Non-static reference to method. But regardless -- use key bindings if you want to trap key presses. [For example](http://stackoverflow.com/questions/8961938/java-keylistener-not-registering-arrow-keys) – Hovercraft Full Of Eels Jun 14 '16 at 02:14
  • How could i set it up so that the key bindings could be changed? – Matt N Jun 14 '16 at 02:18

0 Answers0