Why no Keyboard event?

Hi,
Must be interpreting something wrong :-[.
public class LogInPanel extends JPanel
                        implements ActionListener,
                                   KeyListener,
                                   Observer {
     public LogInPanel (MyModel theModel){
          model = theModel;
          model.addObserver(this);
          // Create okButton and add it to the layout
          JComponent okButton = createButtonPanel();
          add(okButton);
          addKeyListener(this);
        // This method receives OK-button pressed events
     public void actionPerformed(ActionEvent event) {
          command = event.getActionCommand();
          if (OK.equals(command))
               checkFieldsAndLogIn();
     public void keyTyped(KeyEvent ke) {
          System.out.println ("LogInPanel.keyTyped, the " + ke.getKeyLocation() + " key was pressed");
          int keyCode = ke.getKeyCode();
          if ( keyCode == KeyEvent.VK_ENTER) {
               // Do something, like log in.
          // Make sure  the key isn't processed for anything else
          ke.consume();
     private JComponent createButtonPanel() {
          JPanel panel = new JPanel(new GridLayout(0,1));
          JButton okButton = new JButton("OK");
          okButton.setActionCommand(OK);
          okButton.addActionListener(this);
          panel.add(okButton);
          return panel;
     }Nothing is outputted to the console. What am I doing wrong?
TIA
Abel
Edited by: Abel on Jan 25, 2008 3:58 PM
Added example of ActionListener

That could possibly work. But, alas, no keyboard events happen in my code. I have println's in my code, and nothing is written to the console.
     public void keyTyped(KeyEvent ke) {
          System.out.println ("LogInPanel.keyTyped, the " + ke.getKeyLocation() + " key was pressed");
          if ( ke.getKeyChar() == KeyEvent.VK_ENTER) {
               System.out.println ("LogInPanel.keyTyped, the ENTER key was pressed");
     public void keyReleased(KeyEvent ke) {
          System.out.println ("LogInPanel.keyReleased, key " + ke.getKeyCode() + " was released");
      * User has pressed the Enter key, call <code>checkFieldsAndLogIn</code>
     public void keyPressed(KeyEvent ke) {
          System.out.println ("LogInPanel.keyPressed, key " + ke.getKeyCode() + " was pressed");
     }I think this is caused by my LogInPanel not having the focus. If you have a suggestion in that area, I would be obliged. But thanks for your help until now.
Abel

Similar Messages

  • Keyboard Event Listener doesn't work in Browser

    Is there a reason why a keyboard event listener would not work if the flash is embedded in an HTML? The rest of my game is running fine in the background, but I can't launch the movieClip "nextCar." My code is below, if that makes any difference...
    function goNow (event:KeyboardEvent): void {
        thisOtherKey = event.keyCode;
        if (thisOtherKey == 32) {
            nextCar.gotoAndPlay(2);
            parkingQue.play();
            tries++;
    stage.addEventListener(KeyboardEvent.KEY_DOWN, goNow);

    This may be a silly question, but have you tryed clicking on your swf after it opens up in the browser, and then trying the keyboard controls?
    I don't know of any issues that cause event listeners to workwhen debugging, but not in a browser.  So, I'm thinking maybe your just not focused on the swf.

  • Flex 4 does not dispatch keyboard events for ENTER key.

    Hello everyone. I think I have a strange problem with Flex 4 Beta (4.0.0.8909). My application has had event listener for keyUp event for a month now and suddenly (two days ago) I've noticed that keyUp event is not dispatched for ENTER (ALT also) key. Anyone know why? By the way, I've tried this with keyDown event, also 4.0.0.8847 version of SDK - still the same: no keyboard events for ENTER (and ALT) key.
    Here is the sample application that has got this issue:
    <s:Application
       xmlns:fx="http://ns.adobe.com/mxml/2009"
       xmlns:s="library://ns.adobe.com/flex/spark"
       xmlns:mx="library://ns.adobe.com/flex/halo"
       minWidth="640" minHeight="480"
       keyUp="application1_keyUpHandler (event)">
       <fx:Script>
          <![CDATA[
             import mx.controls.Alert;
             protected function application1_keyUpHandler (event: KeyboardEvent):void
                Alert.show ("Key up: " + event.keyCode);
          ]]>
       </fx:Script>
       <s:layout>
          <s:BasicLayout/>
       </s:layout>
       <s:TextArea verticalCenter="0" horizontalCenter="0" width="200"/>
    </s:Application>
    If you run this application and try typing anything in a TextArea you will get alerts with key codes. However, if you press ENTER (or ALT), you will get no alert.
    I'm pretty sure the code above is right so that means there is a bug in latest nightly builds of SDK (i would swhitch to an older build if i knew which one does not have this bug).
    Any ideas?

    Flex harUI wrote:
    That's true, but in this case, I think the text editing code is eating ENTER key in order to prevent parents from seeing it and acting on it (like a submit button).  We'll see if we can find a way around that.
    You can get the ENTER key now by listening in capture phase.
    Alex Harui
    Flex SDK Developer
    Adobe Systems Inc.
    Blog: http://blogs.adobe.com/aharui
    The enter key isn't being disposed of by textedit, the attached example code works without error if you a- remove the alert box and b-set the focus to your text area on initialisation. I agree that pressing the enter key then calling a dialog box will result in the enter key being "gobbled up" as  the enter key is overridden by the dialog box code.
    I think the first suggestion should be to anyone don't use dialogboxes for testing code. If for some reason debugging isn't desirable instead of a trace statement a simple label  can be used as a 'fake' trace.
    David
    Message was edited by: David_F57: I worded this wrong, imho there is no need for a work around, the textarea component works as it should. When intercepting 'system' keycodes there is a need to consider the effect of the intercept and code appropriately to that end.

  • Handling Keyboard Events

    Hi:
    Below is an Air application in which I am trying to catch keyboard events.
    I do catch it once. Subsequently when I try to catch the events, sometimes I must click on the canvas
    to refocus. Sometimes even this does not work. When I choose an option in DropDown list then the handler
    also stops working. Is there something missing in my envent Handler?
    Please advise and thanks for reading and helping.
    <?xml version="1.0" encoding="utf-8"?><mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"layout="absolute" windowComplete="windowComplete();"> <mx:ApplicationControlBar id="dockedBar" dock="true" paddingLeft="0" paddingRight="0"> <mx:ComboBox dataProvider="{stats}" id="statsC" change="statsChangeEvt(event)" /></mx:ApplicationControlBar>
    <mx:Array id="stats"> <mx:Object label="Option 1"/> <mx:Object label="Option 2"/></mx:Array><mx:Script> <![CDATA[ import mx.controls.Alert; private function windowComplete():void{stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);} public function handleKeyDown(event:KeyboardEvent) :void{Alert.show("Key pressed");} private function statsChangeEvt(event:Event):void { Alert.show("Stats Changed")};]]></mx:Script> </mx:WindowedApplication>

    Try listening to the keyDown event in the capture phase.
    addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown, true).
    ComboBox stops the propogation of the event if it is something that it handles. This is why you don't get it in the bubble phase.
    Jason

  • No keyboard Events on a Window

    Hello Java community,
    I can't understand why, if you build a simple Window (not a Frame), all keyboard Events are simply ignored !! Everything acts as if the Window can't get the focus, because no LOST_ or GOT_ FOCUS events are triggered. This means that you can't handle keyboard events with a Window and therefore a Textfield will not work (however it still receive mouse events ??). BUT it perfectly works with a Frame , which extends from Window! Strange isn't it ?
    I've heard on other forums that , to be eligible for focus a Window must have:
    - its owner Frame (the one given in the constructor) :
    * displayed on screen,
    * containing a focusable component.
    - itself, containing a focusable component.
    thus i respect theses limitations, i still can't get any keyboard events
    pleaze help, i am writing a text area component and without keyboard events ...

    Thanks for the answers BUT,
    I have already read the javadoc in every ways and I am sure I respect perfectly all the conditions to have my WINDOW focusable.
    No, there is another problem, a strange one. In fact, my program works fine under Windows I can type characters into my Textfields but once executed under Linux : no keyboard events! Therefore, no character type allowed. I display in the console, all events that are incomming into my Window, and ALL events are ok (mouse, windows..) except keyboards ones. When I press a key, nothing appears in my console, that's why I think keyboards events are caught and not dispatched to the Window.
    I noticed an interresting fact when using my app in Applet. For example, I launched my application with Mozilla (Netscape 4, JRE 1.1). I displayed an empty Window on screen, when my mouse passes over it or when I click, the Java console showed me these events. When I try to hit some keyboard keys, nothing except for certain keys such as F, G, D, J and numeric keys. In fact, these keys are shortcuts to some of the System class (F calls Finalization, G=Garbage Collector, D=Debug Mode...). I truely think that on a Window, all keyboard events are send to the console. Another fact that proved me that i was right : I tried my app with JRE 1.2, and when I wanted to type characters into my TextField (which is on my Window), the typed characters appeared in the console !!!!
    A JAVA-experimented person told me to redirect the standard input to my own inputStream... but how ?
    Any ideas of solutions ?

  • Lock all mouse and keyboard event.

    i am looking ways to lock up all the mouse and keyboard events in windows...do u guy have ways to solve this?

    Do you mean that people should not be able to start other applications, or switch to other running applications, before they have typed the right password into you java program? I don't think that can be done in java - it requires more control over the computer than Java typically gives you. You may have some success with full-screen AWT, though.
    But why not use log-on-systems incorporated in whatever operating system you are using? Or some other netware thingie? Honestly, I think you are trying to reinvent the wheel, and even with tool that's not very appropriate.

  • Losing Keyboard Events

    Hello Forum,
    I have a JFrame that listens for keyboards events which works find. However when I put up a glass pane the keyboard events stop. I'm not setting up any listeners on the glass pane. I know this is vage...was just hoping for any ideas on why this would be happening.
    Thanks for any input.

    the key listener will only work if it has focus. When you put up the glass pane you are taking focus from your fame and putting it on the glass, which doesn't listen so you loose the events.
    So, either add a listener to the glass pane and forward events to the frame, or change focus back to the frame after you put up the glass..

  • Send a keyboard event from labview to C#

    Hi,
    We currently have a program in c# that takes keyboard inputs from a user and will fly a quadrotor. We aim to have a LabView .vi generate keyboard commands based on our experiment and send the commands to the c# code creating a feedback loop where the .vi will keep track of sensor and experimental data.
    Our problem is that we have tried many different methods to send the keyboard commands in LabView. 
    1) http://zone.ni.com/devzone/cda/epd/p/id/3711
    2) http://forums.ni.com/t5/LabVIEW/Send-keyboard-commands-to-another-windows-program/td-p/330670/page/2
    as well as other variations and similar .vi's that do the same thing. Here is an example of a .vi used to press the letter "t" once.
    http://i.imgur.com/hwmjZ.png
    All of them can write the string to a text (open notepad put cursor in blank window) file but none can do it in such a way that it is detected by the c# code. On my own I can open and run the c# code and press keyboard buttons myself and the commands are recognized, so I think it could be an issue with how LabView sends the keyboard events and how c# reads them. Here is the c# code segment that we are using to read the input commands:
    public override List<String> GetPressedButtons()
              KeyboardState state = device.GetCurrentKeyboardState();
              List<String> buttonsPressed = new List<String>();
              foreach (Key key in Enum.GetValues(typeof(Key)))
                        if (state[key])
                                  if (!buttonsPressed.Contains(key.ToString()))
                                            buttonsPressed.Add(key.ToString());
              return buttonsPressed;
    Can anyone help trying to figure out why using the keybd_event function in LabView can not interface correctly with the above detection code in c#? I can provide any code and clarification if you think it can be helpful.
    Thanks,
    Andy

    Hi,
    I can't say with certainty where the problem is or even how many there are. I do know that the KeyboardListener.cs class should work according to what I have read online. I also know that if I press the keyboard myself then the state is changed and the correct action is taken. If I try to issue an event from Labview then the event is not captured. Here is the code, it is rather large ~20 MB.
    https://www.dropbox.com/s/vsvcje1ro364otu/ARDrone.zip
    https://www.dropbox.com/s/p3h3tj8bcqc29gk/Forward_backward0924.vi
    The key listener is in ARDroneInput>Utils>KeyboardListener.cs and the polling takes place in ARDroneInput>KeyboardInput.cs
    The reason I wanted to use keyboard inputs is because the quadrotor we are using takes keyboard commands W,A,S,D,T and L. Initially I thought having Labview issue these commands would be the simplest method. That may not be the case.
    I was just thinking that it is not necessary that key events are sent from Labview. Instead, one could send an array representing the frequency of each button press rather than the button press directly. In that case an array that is updated continuously from Labview will just have to be kept track of in the C# code. The C# can then convert that to whatever control input we want. Can it be easier to send a vector of numbers in real time to C#?
    If you think it is better to establish a connection between Labview and C# using .NET to send keyboard commands (rather than the vector idea above) can you explain that a little more? How does one go about doing that? If you think the vector idea is simpler how should the interface be set-up?
    I just talked with my collegue and we think that maintaing a .txt file in Labview and having C# read it is the best option. We will begin working on that and will update you tomorrow.
    Thanks,
    Andy 

  • Disablying keyboard events in a JFrame.

    Hello,
    How is it possible to disable keyboard events for a specific JFrame and then (after a while) enable events again ?
    thank you,
    Rami

    Look at this program, events are send but you can't see the data in the fields.
    import java.awt.*;
    import java.awt.event.*;
    public class Nok extends Frame
    public Nok()
         super();
         setBounds(6,6,400,300);     
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   dispose();     
                   System.exit(0);
         setLayout(new GridLayout(4,0));     
         add(new TextField("this is a text field"));
         add(new TextArea("this is a text area"));
         add(new Button("this is a button"));
         setVisible(true);
         Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener()
         {     public void eventDispatched(AWTEvent e)
                   System.out.println(""+e);
                   ((KeyEvent)e).consume();
         }   ,AWTEvent.KEY_EVENT_MASK);
    public static void main (String[] args)
         new Nok();  
    Noah
    import java.awt.*;
    import java.awt.event.*;
    public class Nok extends Frame
    public Nok()
         super();
         setBounds(6,6,400,300);     
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
                   dispose();
                   System.exit(0);
         setLayout(new GridLayout(4,0));     
         add(new TextField("this is a text field"));
         add(new TextArea("this is a text area"));
         add(new Button("this is a button"));
         setVisible(true);
         Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener()
         {     public void eventDispatched(AWTEvent e)
                   System.out.println(""+e);
                   ((KeyEvent)e).consume();
         } ,AWTEvent.KEY_EVENT_MASK);
    public static void main (String[] args)
         new Nok();

  • In Flashplayer, I can crossover mouse and keyboard events. In IrfanView I cannot. Can this be fixed?

    My client uses IrfanView to play SWF files. Unfortunately, he does not use Flashplayer. In Flashplayer, I can crossover mouse and keyboard events with no problem. In IrfanView, the second I click a button, the keyboard events are disabled. Is there a fix?

    Hi Ned. I may have posted this issue a bit early, but this problem is also happening in Flashplayer 10. It's not exclusive to IrfanView.
    Here is something that I encountered during my testing, when I jump to scene 6 using the menu button, I have a play button to jump from one frame to the next frame that stops -- the keyboard events start working. But if all I am doing is jumping scene to scene with the mouse button, the keyboard events are disabled.
    I feel as if the keyboard events only work if I am playing frames in the scene. And if all I am doing is jumping scene to scene using the buttons, the keys will disable.
    I set up the mouse buttons inside a movieclip that all the scenes share. The mouse actionscript is in the movieclip. On the main timeline of each scene is an actionscript for the keyboard events, even though I had to change each function name.
    I feel the actionscript is setup pretty simple. I just wish clicking the buttons would not disable the keyboard events. This may sound redundant, but the keyboard events do the same thing if you use the mouse buttons. It's just preference for the client even though he will need to understand that using the mouse buttons override the keyboard events. He doesn't really lose functionality.
    Keyboard actionscripting below:
    import flash.events.KeyboardEvent;
    stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyEvent);
    function onKeyEvent(e:KeyboardEvent):void {
    var character:String=String.fromCharCode(e.charCode);
    if (e.keyCode==72) {
      gotoAndStop(1,"master");
    if (e.charCode==49) {
      gotoAndPlay(1,"Distributor");
    if (e.charCode==50) {
      gotoAndPlay(1,"Mirka");
    if (e.charCode==51) {
      gotoAndPlay(1,"Farm");
    if (e.charCode==52) {
      gotoAndPlay(1,"Check2");
    if (e.charCode==53) {
      gotoAndPlay(1,"Check3");
    if (e.charCode==54) {
      gotoAndPlay(1,"Scene2");
    if (e.charCode==55) {
      gotoAndPlay(1,"Scene1");

  • Can we catch keyboard event triggered by an inputfiled?

    Hi all,
    I have a question here:
    When we are doing the web dynpro abap development, if I want to catch the keyboard triggered by an
    input help and handle it, how can I achieve this?
    e.g.   I have an inputfield on the UI,  if user click "F10" on the keyboard, can I catch this kind of event?
    Thanks and Regards,
    Aaron

    Hi Thomas,
    Yes, I'm trying to acomplish an input help for an inputfield.But, the free programmed value or OVS or dictionary search help can fullfill my needs.Here is the situation:
    I have a inputfield on the UI, and next to that , I have another textview, which should be changed according inputfield. e.g.  the inputfield is a user name, and next to that , is the user id. but we only want the input help for user name. so when user select one row iof the search result table, I want that two fields both filled.
    1. the OVS can't meet my need because I can't change the layout of the search result table, I need a table with a tree in it.
    2. free programmed value help can only send back the value of the inputfield. although maybe I can get the user_id's context attribute name and by hardcoding and send back also the user id. but I don't like hardcoding.
    So, I'm wondering whether I could catch the keyboard event. and handle the F4 help all by myself.
    Do you have some suggestion on this?
    Thanks and Regards,
    Aaron

  • Why multi day events are shown only on the first day in calendar (in month view)

    Why multi day events are shown only on the first day in calendar (in month view)?

    Figured it out - the event has to be marked as full day event in order to be shown in monthly calendar. Disregard my question.

  • Getting keyboard events on ALV grid

    Hi,
    I have an ALV Grid where it is possible to edit data. If user selects a row and presses delete/cut button with mouse event is triggered and I can access those events in code. Although if user selects a row and presses "Del" or "Ctrl + X" then I can't access those events in code. Is there a way to access keyboard events inside my code?

    Have a look at BCALV_GRID_EDIT -> if you select the first checkbox (p_cell = Update on cell change) then you will find that "data_changed" event can catch the line deletion via the keystrokes described.. in the event in this program, you could get the rows deleted from "rr_data_changed->mt_deleted_rows".
    if p_cell = 'X'.
      call method grid1->register_edit_event
        exporting
          i_event_id = cl_gui_alv_grid=>mc_evt_modified.
    else.
    Jonathan

  • [solved] send keyboard event / key to specific background window?

    Hi!
    So... is this possible / how? I'd like to send keyboard events to a window in the background - maybe even in regular intervals. While I'm dong something else, in another window (or nothing).
    Thx!
    Last edited by whoops (2011-07-21 11:05:44)

    Actually I'm thinking, maybe there is a totally another (better?) way to do what you want. I usually find that automatizing tasks in linux differs very much from the windows experinece, most of the times scripting is the most powerful and easy way of doing things. So if you describe to us what you want to accomplish, maybe some experienced linux gurus would give you some advices that sets you off course from sending keys and mouse events. I used to do that in windows with autohotkey, but now in linux there was no need for that so far ever, except for using system wide abbreviations with autokey.

  • Handling keyboard events in applets?! Possible?!

    Hello,
    I wrote a little game that uses keyboard handling events. It is an applet that can also standalone as an application. When i run the program as a standalone application, it handles keyboard inputs fine. ie...i can press the left and right arrow keys and something happens.
    But when i run my program as an applet in a web browser, the applet starts up correctly but does not handle any keyboard events. It only handles mouse events. For instance, if i press the up and down arrow keys, the browser window scrolls up and down!!! And the up and down arrow keys have a specific purpose in my applet.
    QUESTION: how do i get my applet to accept keyboard inputs such as UP,DOWN, LEFT, RIGHT?

    Hmm something went wrong w/ my post so i hope this doesnt show up twice.
    Hey thanks a lot for helping me out. The applet/application is large so here is the main() method and the keyboard event handling class code. My question is how come the keyboard events get properly handled when i run it as a standalone application, but keyboard events go to the browser when i run it as an applet? I would post my entire code but it's over 1000 lines and spread out over 8 files. hehehe.
    Here is main():
      public static void main(String[] args)
          MyProgram applet = new MyProgram();
          applet.isStandalone = true;
          JFrame frame = new JFrame();
          frame.setTitle("Physics: Kinematics");
          frame.getContentPane().add(applet, BorderLayout.CENTER);
          applet.init();                        // initialize the applet inside frame
          applet.addKeyListener(kbHandler);     // kbHandler is a keyboard handling object
          applet.start();
          frame.setSize(APPLETWIDTH,APPLETHEIGHT);
          Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
          frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
          frame.setVisible(true);
          // private inner class to terminate the Application when frame closes
          frame.addWindowListener(
            new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
          frame.show();
       }"kbHandler" is the keyboard event handling object. It gets initialized in the applet.init() method.
    kbHandler = new BMkeyboardHandler();And here is the keyboard event handling code:
    // ===== keyboard event handler ===========
       private class BMkeyboardHandler implements KeyListener
            public void keyPressed(KeyEvent e)
                pushedKey = e.getKeyCode();
                // General administrative key actions
                if(pushedKey == KE.VK_H)
                    actionArea.toggleHelpMenu();
                    actionArea.repaint();
                else if(pushedKey == KE.VK_C)
                    actionArea.toggleCtrlMenu();
                    actionArea.repaint();
         }So there it is. Again, the program handles events fine as a standalone application. But running it as an applet in a browser (and even the appletviewer) doesnt let me handle keystrokes.

Maybe you are looking for

  • Why is my MacBook running so slowly?

    Here is the information about my computer. I like to problem solve but am not a computer geek so if you have information to share, please put it in a layman's language! Thank you in advance for any help you offer. EtreCheck version: 1.9.12 (48) Repor

  • Errors encounted during installation. (U44M1P7)

    Happens when I try to update: 06/18/13 14:11:38:326 | [INFO] |  | OOBE | DE |  |  |  | 10644 | *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* =*=*=*=*=*=*=*=* 06/18/13 14:11:38:326 | [INFO] |  | OOBE | DE |  |  |  | 10644 | Vis

  • Registered a new user-name for BB app would and it says use the username associated with this smartphone

    i have an old email which i used to use it back home on another blackberry before, since i bought the news blackberry 9900 i use that username and it working till now, but i want to register it with another one, i have register and i use it in blackb

  • User Manual for Photoshop CS6

    Can someone please send me a link where I can download the user manual for Photoshop CS6.  I'm not looking for individual help topics but an actual user manual.  I couldn't find it in the online documentation.  Thanks.

  • Steps Workflow aren't completing correctly

    Hi everyone, So I have an InfoPath form with a field in a form library titled "Manager ID" and it's exported from the form using Property Promotion. I have another field called "Manager Name" which is a person field in the same library. I have a work