How can I add or remove 60 from methods depending on what arrow key is pressed?

I want to add or remove 60 from “charaposx101” or “charaposy101” depending on what arrow key is being pressed while the code (JFrame) is running. Here are some snipets of code I think are related to the question, sorry if its bearly legible, Im very new to coding

class MainFrame extends JComponent {
public int charaposx101=0;
public int charaposy101=0;
}
public class Main {
    public static void main(String[] args) {
        JFrame Frame = new JFrame("game");
        Frame.setSize(675, 700);
        Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Frame.getContentPane().add(new MainFrame ());
        Frame.setVisible(true);
        Frame.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_UP) {
                    System.out.println("Up Arrrow-Key is pressed!");

                }
                else if (keyCode == KeyEvent.VK_DOWN) {
                    System.out.println("Down Arrrow-Key is pressed!");
                }
                else if (keyCode == KeyEvent.VK_LEFT) {
                    System.out.println("Left Arrrow-Key is pressed!");
                }
                else if (keyCode == KeyEvent.VK_RIGHT) {
                    System.out.println("Right Arrrow-Key is pressed!");
                }
            }
        }
        );
    }
}

I tried adding a new method to MainFrame

public void changeCharPos(){
(not needed)
}

but when I tried accessing it from Main, it would always give me an error

Frame.changeCharPos()
//or
MainFrame.changeCharPos()
//or
Main.changeCharPos()

  • 1

    See stackoverflow.com/questions/11993077/…

    – 

Here you have a method definition:

public void changeCharPos(){
(not needed)
}

And here is the invocation:

Frame.changeCharPos()
//or
MainFrame.changeCharPos()
//or
Main.changeCharPos()

The problem is that your invocation (best try is MainFrame.changeCharPos()) actually refences the class and tries to invoke the method. This would work, had you specified the method as public void static changeCharPos().

Since you did not, you must create an instance of MainFrame and call the method on that, such as

new MainFrame().changeCharPos();

MainFrame m = new MainFrame();
m.changeCharPos();

BTW, it would have been good if you shared the error itself. It should be a compiler error.

Leave a Comment