Detect key events on anything

If I have a JFrame with many components on it, how do I detect if a key is pressed, without having to add a listener to every component? For example, how can I check for the escape key being pressed, but not having to have componentN.addKeyListener(this); for everything?
Thanks
US101

The correct way to collect the key events is the following:
from java 1.2 to java 1.3 use the FocusManager. This class can be found in the javax.swing package. You would then need to extend the DefaultFocusManager and override specific behavior.
for java 1.4 use the KeyBoardFocusManager. This class can be found in the java.awt package.
Please see the following for a better explanation:
http://java.sun.com/j2se/1.4/docs/api/java/awt/doc-files/FocusSpec.html
Thanks for your time,
Nate

Similar Messages

  • Detecting key events and setting caret position from a Document model

    Hello, I have created a "masked" JTextField that contains specific formatting (these subclasses were created prior to the advent of Sun's implementation of masked fields, and are used extensively throughout my system, so I can't easily implement Sun's version at this time)
    At any rate, here is the problem:
    Consider the following "masked" field contents (date USA format):
    The user keyboard input is:
    "10252002", which results in the text field display of "10/25/2002"
    The user presses the "delete" key in the first position of the masked field. The following result is "0/25/2002".
    This is undesirable, since all the contents of the field have shifted to the left by one position, so the first "/" is now in position 2, instead of position 3. Also, the length of the field is now 9, instead of 10.
    The field should really have the following contents: "02/52/002_", and the cursor should remain on the first position of the text field.
    I believe need for the Document model to be able to differentiate between a "back space", and a "delete", so that my overridden "remove" method in my PlainDocument subclass can handle
    insertion/repositioning of "masked literal" characters correctly, and also control the cursor movement accordingly.
    What would be the best way to handle this?

    I would re-post to the Flex Data Services forum.

  • How to detect key board event

    HI,
    How to detect keyboard event (Like CTRL key press shift key press) in Swing�any can any body suggest classes and interface for that�.
    Thanks

    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to use Key Bindings

  • Getting key events without a jcomponent...

    Is it possible to get key events without adding a keylistener to a jpanel? I want a class of mine to manage input of it's own, but it has no reference to a jpanel. They don't necessarily have to be KeyEvents, but just some way to detect if a key has been pressed (like the arrow keys). How can I do this? Thanks.

    Lots of components can listen for key events.
    What does your class subclass?It doesn't subclass anything. I am creating a custom menu system for my game using images I have made for the tileset. I would like it to handle some keyboard events of its own. (Like if the down arrow is pressed, it will move the focus down to the next component on its own). Right now I am currently passing the key events from my fullscreen jpanel to the menu class and it is handling them that way. Thanks.

  • NIO Selector object can't detect OP_ACCEPT event in time.

    We developed a server with Java NIO. we use a special thread to accept new SocketChannel object, read data, write data with a Selector object in server side. The client side is similar with the server side, it also use a special thread to connect to server, read data, write data.
    Now, we found sometimes the time that the socket channel object can't be accepted in server side in time. for example:
    the client side:(output after socketchannel.finishConnect is true)
    11:20:27.937 Finished connect to <remote:/127.0.0.1:9433,local:/127.0.0.1:3602> .
    the server side:(output after serversocketchannel.accept method)
    11:33:11.93 Accepted connection from /127.0.0.1:3602.
    From the log, we knew that the client created a socket channel object and finished connect at 11:20:27.937 but selector object detected this OP_ACCEPT event and accept this socket channel at 11:33:11.93. this process need 13 minutes.
    No server can accept this so long delay. this issue happen only when the machine is in high load.
    I reproduce it by the below steps:
    1, start 3 servers in one machine.
    2, run 40 threads to access one server. the machine is in very high load, then quickly this issue happen.
    by the way, the implement of server side is below:
    while (!shutdown) {
    try {
    int readyCount;
    try {
    readyCount = selector.select();
    } catch (java.nio.channels.ClosedSelectorException ex) {
    readyCount = -1;
    if (readyCount == -1 || isWindowsChannelBug4881228(readyCount)) {
    // Reset the selector
    logger.error("windows channel bug 4881228");
    } else if (readyCount == 0) {
    logger.debug("select wakeup");
    } else {
    Iterator keyIter = selector.selectedKeys().iterator();
    while (keyIter.hasNext()) {
    SelectionKey key = (SelectionKey) keyIter.next();
    keyIter.remove();
    if (key.isConnectable()) {
    ((ChannelConnection) key.attachment()).finishConnect();
    if (!key.isValid()) {
    continue;
    if (key.isAcceptable()) {
    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
    try {
    SSLEngine sslEngine = null;
    if (ssc == sslSocketChannel) {
    sslEngine = sslContext.createSSLEngine();
    sslEngine.setWantClientAuth(true);
    sslEngine.setUseClientMode(false);
    ServerChannelConnection conn =
    new ServerChannelConnection(this, ssc.accept(), sslEngine);
    conn.setConnectTime(System.currentTimeMillis());
    conn.registerForRead(selector);
    } catch (IOException ex) {
    if (!key.isValid()) {
    continue;
    if (key.isReadable()) {
    try {
    ((ChannelConnection) key.attachment()).processInput();
    catch (Throwable ex) {
    logger.error(ex);
    if (!key.isValid()) {
    continue;
    if (key.isWritable()) {
    try {
    ((ChannelConnection) key.attachment()).processOutput();
    catch (Throwable ex) {
    IOException iex=new IOException(msg(FailedWriteResponse));
    iex.initCause(ex);
    logger.error(iex);
    if (!key.isValid()) {
    continue;
    processPendingRequests();
    catch (Throwable ex) {
    logger.error(ex.getMessage(), ex);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException ex2) {
    // ignore
    The client side is similar with the up.
    I can't understand it. Normally, the selector should detected OP_ACCEPT event quickly. but why not?
    Anyone who met this issue?

    You have an empty catch{} block for IOExceptions when handling isAcceptable(). So the prima facie presumption is that an error condition is arising, that you are ignoring. Fix that first and retest.
    After that, if you still have a problem, I have some comments.
    1. Create the SSLEngine and/or the ServerChannelConnection after accepting the connection, not before, and only if you got a non-null accepted channel. It is still valid for accept() to return null after you get OP_ACCEPT.
    2. Get rid of the sleep() in the exception handler - what's that for?
    3. select() for a specific timeout, not forever, and use the selectCount == 0 case to do something useful such as scanning for idle connections that you might want to drop.
    3. Catch IOException explicitly as well as Throwable, in the outer loop, not per operation, and close the current key's channel if you get it. You can't do anything more with a channel that's had an IOException of any kind, except a SocketTimeoutException, and you won't get that in non-blocking mode.

  • No key event when compose keys are pressed

    I am supporting a legacy application for Sabre which maps some of the keys differently. For example, on a French keyboard the Compose key which is used to put a ^ on top of the vowel characters is to be remapped to produce a special character called a "Change Character" that has a special use for reservation agents that use Sabre
    The problem is, the first time you press the ^ compose key there is no key event apparently because the VM figures it doesn't yet know what key to report, it is expecting you to press a character such as 'o' and then you get an 'o' with a '^' on top of it.
    If you press the ^ compose key a second time, you get the following key events:
    keyPressed
    keyTyped
    keyTyped
    keyReleased
    On the screen you will see two ^ characters appear. Currently I remap the ^ character to the "Change Character", and I suppress the second keyTyped event so that I only get one character. The problem is that the user ends up having to press the key twice to get one "Change Character."
    I have no fix for this problem because there is no key event produced when they press the ^ compose key the first time.
    By the way, this behavior appears to have been introduced with jdk 1.3. The older jdk did produce a key event the first time you pressed the compose key. I would expect that this behavior was considered to be a bug and was fixed in jdk 1.3.
    Is there some other way to detect when the user presses a compose key? If not, is it possible for future jdk releases to report a keyPressed event when a compose key is pressed? This event would not cause a character to appear on the screen, but would allow programs to detect when the compose key is pressed.
    There is already a key on the French keyboard that behaves this way. It is the key to the left of the '1' key and it has the pipe symbol on it. If you press Shift plus this pipe key, no character is produces but a keyPressed event with a keycode of 222 is produced. I merely point this out to show that there is a way to report key events whithout producing output on the screen.
    Thanks, Brian Bruderer

    I don't know if this actually helps, but it seems that you can bind an Action to a dead key like the circumflex of the French keyboard
    Keymap keymap = textPane.addKeymap("MyEmacsBindings", textPane.getKeymap());
    Action action = getActionByName(DefaultEditorKit.beginAction );
    KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_DEAD_CIRCUMFLEX);
    keymap.addActionForKeyStroke(key, action);I saw this on a Swing tutorial and modified it slightly. Have a look at it :
    http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html
    Chris

  • Handling Enter key event in JTable

    Hi...
    This is particularly for the user "VIRAVAN"...
    I have followed your method ,and got results too.. but the
    processKeyBinding(.. method is called 4 times,same problem addressed by you before, but I didn't understood it...
    Please help me...
    Here is my code...
    protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,int condition, boolean pressed)
    System.out.println("Wait");
    if (ks == KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0))
    int selRow = getSelectedRow();
    int rowCount = getRowCount();
    int selCol = getSelectedColumn();
    String val =(String)getValueAt(selRow,selCol);
    boolean b= getCellEditor(selRow,selCol).stopCellEditing();
    System.out.println(b);
    System.out.println(rowCount-1 + " "+ selRow + " " + getSelectedColumn());
    if((!val.equals("")) && selRow==rowCount-1)
    System.out.println(rowCount-1 + " "+ getSelectedRow()+ " " + getSelectedColumn());
    blank1 = new String[columns];
    for(int p=0;p<columns;p++)
    blank1[p]="";
    Diary.this.datarows.addElement(blank1);
    // dataModel.fireTableStructureChanged();
    //dataModel.fireTableDataChanged();
    Diary.this.dataModel.fireTableChanged(null);
    else if(ks ==KeyStroke.getKeyStroke(KeyEvent.VK_1,0))
    System.out.println("One One One One ");
    return super.processKeyBinding(ks,e,condition,pressed);

    It's been a while since I looked at the code, but essentially there are three key event types:
    1) key pressed,
    2) key typed,
    3) key released.
    So I would expect the processKeyBind to see all three of them. However, ks==KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) is true only when a key typed event is detected (the other types can be ignored by passing it up the food chain where they will eventually be consumed). Now...., if I understand you correctly, you want to terminate edit on the present of Enter key, right? Here is how I'd suggest you do:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }Ok.... now, it appears that you want to do something else also... i.e., add a new row to the table if the editing row is the last row and the editing column is the last column of the last row. You can't do that in the same thread (i.e., you must wait until the update in the current thread is completed). So, what you must do is use the SwingUtilities.InvokeLater, like this:
       protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
          if (isEditing()) {
             Component editorComponent=getEditorComponent();
             editorComponent.stopCellEditing();
             if (getEditingRow()+1==getRowCount() && getEditingColumn()+1==getColumnCount()) {
                SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
    // put the code for adding new row here
             return true;
          return super.processKeyBinding(ks,e,condition,pressed);
       }OK?
    ;o)
    V.V.
    PS: posted code is untest but should work!

  • Detect key status of '*', '#' & '0' of using getKeyStates() method

    Any know the how to get key status if using getKeyStates() method of GameCanvas object in pressing keys "*", '0' & '#' (as I know, the method just can detect key pressing of number 1~9)? If no, is there any method able to do so (similar function of getKeyStates() but not keyPressed()) or how to modify the method able to function it ?

    Hello,
    Sorry for the confusion... let me try to be more clear...
    So, my test campaign for a specific UUT is composed of about a dozen sequences, which can be run independently. But I created another sequence, to work as a "batch", calling all these dozen sequences.
    Pretty much what it does is:
    1) Call first sequence in new execution
    2) Wait for execution to finish
    3) Check results of execution
    4) Add results to report
    5) Wait 10 seconds
    6) Call second sequence in new execution
    7) So on...
    So, for each new execution, I have a dedicated report, which is exaclty what I want. But for my "batch" sequence, I would like to be able to get a report saying which executions passed or failed, so I don't have to open the reports for each execution individually.
    The way I'm doing this (in step 3 above) is with the following expression:
    ( Find( RunState.PreviousStep.ResultStatus, "Passed", 0, True, False ) >= 0 ) ) ? "Passed" : "Failed"
    This way, anything different than "Passed" would give me a "Failed" result for that execution, and that's fine. The problem is that when one of the executions is terminated before it's finished, the PreviousStep.ResultStatus is giving me "Passed".
    I didn't know about the GetStates() method... Looks promissing! I'll give it a try.

  • How to handle key events in iphone

    I want to be able to detect physical keyboard (e.g. bluetooth) events in an iOS app.
    In Mac, there is a class NSEvent which handles both keyboard and mouse events, and in ios (iphone/ipad) the counterpart of NSEvent is UIEvent which handles only touch events. I know ios API does not provide this functionality, but how can i handle key events in iphone???

    in my application header part of the page is common of all page. header.jsff contains comandmenuItem named "proceduralhelp". if I click proceduralhelp a pop up opens .
    in my login page when first time I open popup and press escape popup is not closing.
    rest of the cases after login escpe will cose the popup.
    only on the loginpage that to for the first time it is not closing when pressing up on escape key. (then we click on close button. and once again open the popup in loginpage now if we press escape it works).
    Thanks,
    Raghavendra.

  • JPanel cannot recieve Key Events?

    Hi. I'm trying to make a simple game, which recieves input from the arrow keys and spacebar. The drawing is done inside a paintComponent() method in a JPanel. Therefore, the key events should also be handled in the same JPanel. I can call the addKeyListener() method on the JPanel, but it does not recieve key events. I've tried calling setFocusable(true) but it doesn't seem to do anything. If JPanel can't recieve key events (it can recieve mouse events fine), I have to handle the events in the JFrame, which I'm hesitant to do. My book does it in an applet and applets can recieve key events fine, but I want to make an application.
    No working source code here, try to figure out what I'm saying.
    Thanks.

    Please help me. I did help you. I gave you a link to the tutorial that shows that proper way to do this.
    All Swing components use Key Bindings so you might as well take the time to understand how they work.
    Anyway, based on your vague description of the problem we can't help you because we don't know the details of your code.

  • Capture desktop key event to control my screen capture app

    I want to write a screen capture program to capture screen when I am playing fullscreen game or other desktop window application. But the java screen capture program can only receive key or mouse event when it is focused. So how do I capture key event when I am focusing other app or fullscreen app?
    Do I have to use JNI and call some OS specific API. My target OS is WinXP. Help or suggestions are appreciated!!

    Hi All,
    I was wondering if there is a way to capture the top-most
    window or dialog box. This is something that will
    generally be running outside of the JVM....We,
    as programmers, need a Rectangle instance that describes the area
    of interest to be captured (i.e., location and size).
    Thus, a routine that interfaces to the Native windowing system (Toolkit?)
    might look something like:
    Rectangle rect = tk.getRectangleForTopMostComponent();
    Does anything like this exist?
    Thanks!
    - DocJava

  • KeyListener does not capture Arrow key Events in textField

    Love................
    I added a key listener to TextField it does not detect
    Arrow Keys events in keyTyped, KeyPressed,KeyReleased methods
    why?????
    I want to shift focus from a textfield to other component
    on capturing Arrow key Pressed How

    Here is a Java demo where it works since it is not a printable character you must get the keyCode:
    http://java.sun.com/docs/books/tutorial/uiswing/events/example-swing/index.html#KeyEventDemo
    public class KeyEventDemo ... implements KeyListener ... {
    ...//where initialization occurs:
         typingArea = new JTextField(20);
         typingArea.addKeyListener(this);
    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
         displayInfo(e, "KEY TYPED: ");
    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
         displayInfo(e, "KEY PRESSED: ");
    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {
         displayInfo(e, "KEY RELEASED: ");
    protected void displayInfo(KeyEvent e, String s){
         char c = e.getKeyChar();
         int keyCode = e.getKeyCode();
         int modifiers = e.getModifiers();
         tmpString = KeyEvent.getKeyModifiersText(modifiers);
         ...//display information about the KeyEvent...
    }

  • How to distinguish is cell get key event or mouse event in table?

    Hi!
    I have a JTable.
    1.Select cell and double click. As result caret is show
    2.Select cell and start type. As result caret is show
    How distinguish is caret is show, because cell get mouse event or key event?
    Thank you.

    Hm ...
    the problem with the key events is, that they are partically taking place in an editor component - but the double click of the mouse clicked on a cell, which is not currently edited, can be get by a MouseListener added to the JTable.
    My idea to that is as follows - hold the double_clicked state in a boolean variable hold by your JTable subclass - it is set by a MouseListener added to the JTable - and reset by the overwritten prepareEditor(...) method. This method should do the following:
    // say, double_clicked is a boolean field in your JTable subclass
    public Component prepareEditor(TableCellEditor editor,int row,int column) {
    Component c = super.prepareEditor(editor,row,column);
    if ((!double_clicked)&&(c instanceof JTextField)) { ((JTextField) c).setText(""); }
    double_clicked = false;
    return c;
    }now you have only to implement an add a MouseListener to your JTable subclass which detects this double click and sets the double_clicked field accordingly.
    This is an idea on the fly - hope it is helpful for you.
    greetings Marsian

  • Capture Key events

    I am trying to create a program to capture key events, regardless of where the focus is. For example, any time the user presses ctrl-t, I would like to call a particular method, if the user is in Microsoft Word, Internet Explorer, Halo, or any other application. However, a glass pane would not work, because all other key events will be needed by the current application. This would be identical to Microsoft' s ctrl-alt-del and Microsoft's alt-tab. Any ideas would be greatly appriciated. Post here or E-mail be at [email protected]

    This is not true, think of all the keylogger programs out there that allow you to do this.
    It's not a security issue.
    I also am wondering how to capture a key on a java application without it having focus. An example is a timer in a game. I should be able to be in a full screen game and hit F1 or Home or whatever I choose and have a timer start that will ding at me in 1 minute to let me know that my time is up.
    It is in a way similar to CTRL ALT DEL in that you don't ahve to be focused on anything in particular to use it but that isn't really the best analogy.
    If anyone can point me in the right direction to figure out how I would go about this, please tell me. Or if it is not possible for a program written in java to capture keypress without focus I would like to know that as well.
    You can do this in C and C++ but I would like to just add it in to an existing java program, thanks.

  • Catch a key event in JFrame

    hi,
    i am coding a GUI application for some FSM(Finite State Machine) simulation purpose. the app can load the FSM and display it. i can selecte some part of FSM and using "delete" key to delete the selected states. i did register the KeyEventListener to the the JFrame. but when i try to press the "del" key the app doesn't do anything. after few tests, i think JFrame never listene to my key event. how can i make it possible to let the JFrame to listene to my "key event"?
    Thanks~~~

    Read this, it is very useful for things like this:
    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings
    In your case you can add a key binding to the frame's root pane, and bind the delete key to the action you want to perform.

Maybe you are looking for

  • Issue with Setting Application Item

    Hi All, I have an issue with setting the value of application item G_USER_ID as part of the login process. I use customized authentication for login. I have created an application item G_USER_ID, and in my CUSTOM_AUTH procedure, I am setting its valu

  • Extended Withholding Tax Certificate Printing

    hi, i configured & checked upto withholding tax in invoice poting & payment posting now i want to configure the things for certicate printing like number group, number range etc,,, can any body help me out in sending sequence of configuration documen

  • How to blink an indicator under certain conditions

    Hello all, My code right now checks our flow controller setpoints, subtracts the readback value, and takes the absolute value. If the value is greater than 30% off, then the indicator blinks.  The problem I have is that during testing, sometimes the

  • MSS PCR(Personnel Change Request) Report

    Hi Experts, We have configured MSS successfully, Now the reqirement is that we require a report which keeps the track of all requests generated during MSS PCR, like which request, who requested, approver, status of the request....etc..... Is there an

  • How to make show iChat date as well in the log

    iChat shows in the protocol the time. I want also to see the date, because we use iChat mainly for inter office communication and sometimes I want to know at what date a certain message has been sent. How can I get that option set?