Tuesday, May 7, 2013

Java Keybinding Tutorial

While making the graphics test, I ran into the problem of key listening. I tried the Java key listening API to no avail. Later on, a programmer that I know showed me how to do what I was trying to achieve with Java key binding. I went online and found that many other people were having the very same problem, so I decided to make a quick tutorial of what he showed me.

First you are going to need a main class that extends the JPanel class. Inside the main function (which you should place in this class) put the following code.

JFrame frame = new JFrame("Title of JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ClassName classInstance = new ClassName();
frame.getContentPane().add(classInstance);

That code will just provide you with a basic frame so that you can add your panel to it, and an instance of your class. This code does nothing for the actual key binding, and that is why you need the next section of code.

classInstance.getInputMap().put(KeyStroke.getKeyStroke('a'), "doSomething");
Action pressedAction = new AbstractAction(){

    @Override
    public void actionPerformed(ActionEvent arg0) {

//Here you put the code that is run when you press the key

}
       
};
classInstance.getActionMap().put("doSomething", pressedAction);

The above code is for the actual key binding mechanics. You can fit this to your needs by replacing a with whatever keystroke you are detecting.

I hope that everyone liked that tutorial, and the graphics test will be released soon!



No comments:

Post a Comment