I am writing a program which needs keyboard events. I have tried googling, but none of the sites seem to be very clear. So how can I set up a key listener which will execute a block of code when a key is pressed?
Printable View
I am writing a program which needs keyboard events. I have tried googling, but none of the sites seem to be very clear. So how can I set up a key listener which will execute a block of code when a key is pressed?
One key question though is are you trying to capture keystrokes even if the application doesn't have focus, in other words a keylogger? If so, Java is not the tool for this job.
No I am not trying to create a keylistener.
And thank for the link, but it gave no instructions on how to create a keylistener, and when I tried using relevant parts from the example code, I got an error.
The links give all the general information on how to create key listeners and key bindings. My guess is that you're trying to use it wrong, but to be able to tell you more, we'd need to see your code. You would do well to give us a lot more information about your problem.
Those two lines both yielded an error, asking me to create a class typing area.Code:public class main implements KeyListener {
typingArea = new JTextField(20);
typingArea.addKeyListener(this);
Also didnt work, although there was no error messageCode:public void keyTyped(KeyEvent e) {
System.out.println(e);
}
No surprise: that's not viable Java code. This has nothing to do with Swing and all to do with proper Java. You're using a variable, typingArea before declaring it, and then you're trying to call methods on it outside of a method, constructor or similar block. You'll find tutorials on the basics of Java here: http://download.oracle.com/javase/tu...ybigindex.html
Thanks for that, I am now not getting any errors. I have the following code:
I don't get any errors when I run, but nothing seems to happen when I press any keysCode:public class ball {
...
public ball (){
...
JTextField typingArea = new JTextField(20);
typingArea.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
public void keyPressed(KeyEvent e) {
System.out.println(e);
//throw new UnsupportedOperationException("Not supported yet.");
}
public void keyReleased(KeyEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
});
}
I don't know why your code isn't working based on what you've posted, and you may need to create and post a minimal compilable runnable example (an SSCCE) that we can run, modify and correct to be able to help you. Please see the link.
But more importantly, what functionality are you trying to give your program? KeyListener may not be the best fit depending on what you're trying to do.
The purpose of the key listeners is to use the arrow keys on the keyboard to move an object around the screen.Code:import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class main {
public static void main(String[] args) {
JFrame win;
Container contentPane;
Graphics g;
win = new JFrame("Clock");
win.setSize(1200, 800);
win.setLocation(0, 0);
win.setVisible(true);
contentPane = win.getContentPane();
g = contentPane.getGraphics();
JTextField typingArea = new JTextField(20);
typingArea.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
System.out.println(e);
}
public void keyReleased(KeyEvent e) {
}
});
}
}
1. Never never never use getGraphics() of a Component. Or at least not until you know as much about as Fubarable does (I don't, so I don't use it)
2. A Component that isn't added to a hierarchy that's made visible doesn't receive events. Not keyboard events, not mouse events, not focus events, nada.
db
Ok, thanks for the advice
Do you have any suggestions for what I should use instead?
I have tried adding
on the 4th line from the bottom and still nothing happens.Code:contentPane.add(typingArea);
Use key bindings for this instead since they're a higher level construct, will work even if the component they are added to doesn't have the focus. The tutorials will show you how to use these.
edit: for e.g., http://www.java-forums.org/new-java/...s-pressed.html
Thanks for that, it was very useful.
Just one question:
How do I create a javax.swing.Action?
Ok, I've tried taking parts of that but really didn't understand what most of it did. I have already defined the method I want to be invoked when a key is pressed if that is any help.
Good for you, then you have a plan! ;)
To better understand key bindings, you'll need to study the tutorials that have been linked above. If you don't understand what's in the tutorial, then please come on back and ask for clarification, and we'll be glad to help.
Best of luck!
Just to clarify:
To create a javax.swing.Action do I create a separate class that extneds AbstractAction then override
and put the code that I want to execute in that method?Code:public void actionPerformed(ActionEvent arg0)
You could create a separate stand-alone class for this, yes, but if the code held in the class is small, then an alternative is to create a private inner class to call your method, or another way is to create an anonymous inner class, an object whose class has no name but is created "in-line" when needed. So assuming you have a method called, callMyMethod():
Code:private void callMyMethod() {
// TODO code that gets called on button push
}
A private inner class could look like so:
Code:private class MyPrivateInnerClass extends AbstractAction {
@Override
public void actionPerformed(ActionEvent arg0) {
callMyMethod();
}
}
and then could be used like so:
Code:myComponent.getActionMap().put("Some String that's used with InputMap", new MyPrivateInnerClass());
Or to use an anonymous inner class with key binding:
Code:myComponent.getActionMap().put("Some String that's used with InputMap", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callMyMethod();
}
});
We often use anonymous inner classes when adding ActionListeners to JButtons:
Code:JButton button = new JButton(new ActionListener() {
public void actionPerformed(ActionEvent e) {
callMyMethod();
}
});
Am I correct in thinking that to make a key binding I need a component which I use getInputMap() and getActionMap() on?