JPanel can't receive key events

I have a single JPanel added to the content pane of a JFrame.
I want to itercept key events by adding a KeyListener to the JPanel.
If I do it, I don't receive key events.
To solve the problem I identified two ways:
- add the KeyListener to the JFrame's content pane
- invoke setFocusable(true) on the JPanel (available only since 1.4)
I can't use the former because I want to bind the the KeyListener to the JPanel, and I can't use the latter because I don't want to have dependencies on jdk 1.4.
Can anyone suggest a way to solve the problem as simple as calling setFocusable() but available also for older versions of java?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyListenTest {
     public static void main(String[] args) {
          JPanel panel = new JPanel();
          panel.addKeyListener(new KeyAdapter() {
               public void keyTyped(KeyEvent e) {
                    System.out.println(e);
          JFrame frame = new JFrame();
          frame.getContentPane().add(panel);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400,300);
          frame.setVisible(true);
          panel.requestFocus();
}The panel must be displayable and visible, so you have to make the call after frame.setVisible(true), however if you don't have any other components that will take the focus away from your panel, this should do it for you. If you want the use to be able to shift focus to your panel, then just add a mouse listener to the panel with a mousePressed(MouseEvent) method that calls the requestFocus() method on the panel.

Similar Messages

  • Eventhandlers of children of application can not receive custom event dispatched by application

    Hello dear Adobe community,
    hope you can help me with this issue.
    When the application dispatches a custom event, the child uicomponent can only receive the event by using Application.application.addEventListener or systemManager.addEventListener. Simply adding a listener, without application or systemmanager, does not allow the event to be received by the child component.
    I want to be able to use the addEventListener and removeEventListener without SystemManager or Application.application, or could you provide a better workaround? How can I use the addEventListener, do I need to overwrite EventDispatcher, which I wouldnt like to do?
    Just to clarifiy, if i remove the systemManager in front of addEventListener(CustomEventOne.EventOne,sysManHandleCE,false) it will not add it and will not fire. 
    The code below is an example for this problem that the event is not getting fired in the right moment. The mainapplication got only a button with the customEventOne that gets dispatched.
    public
    class MyCanvas extends Canvas{
    public function MyCanvas()
    super();
    width=300;
    height=300;
    addEventListener(FlexEvent.CREATION_COMPLETE,handleCC,false,0,true);
    private function handleCC(event:FlexEvent):void
    removeEventListener(FlexEvent.CREATION_COMPLETE,handleCC);
    addEventListener(CustomEventOne.EventOne,handleCE,false,0,true);
    addEventListener(Event.REMOVED_FROM_STAGE,handleEvt,false,0,true);
    systemManager.addeventListener(CustomEventOne.eventOne,sysManHandleCE,false,0,true);
    private function handleEvt(event:Event):void
    trace("In removed from stage handler");
    systemManager.removeEventListener(CustomEventOne.EventOne,sysManHandleCE);
    trace(hasEventListener(FlexEvent.CREATION_COMPLETE));
    trace(hasEventListener(CustomEventOne.EventOne));
    trace(hasEventListener(Event.REMOVED_FROM_STAGE));
    private function handleCE(event:CustomEventOne):void
    trace("I got it");
    private function sysManHandleCE(event:CustomEventOne):void
    trace("I got it");
    public class CustomEventOne extends Event
    public static const EventOne:String = "EventOne";
    public function CustomEventOne(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
    super(type, bubbles, cancelable);
    override public functionclone():Event
    return newCustomEventOne(type,bubbles,cancelable);
    Thank you in advance,
    Michael

    I think you need to look at event propogation. The object that dispatches an event will be sitting on the display tree. The event propagates up the tree to the roots. Your canvas should be attached to the application, but even then it sits lower in the tree branches than the event dispatcher, so it won't see the event being dispatched because the event is not propagated to the children of the object that dispatches it but to the parent of the object that dispatches it.
    So, your canvas is a child of the application, but dispatching the event from the application means that the canvas doesn't see it because events are notified up the tree using the parent link, not the child links.
    You may wish to investigate how the display list and event propagation works and then the MVC pattern.
    Paul

  • JPanel can't receive KeyEvent?

    Hi,
    I have add a KeyListener to my JPanel,but methods of the listener does not invoked when keyboard is typing.
    Is JPanel can't receive KeyEvent?

    try add a overlay method:
    public boolean isFocusTraversable() { return true;}

  • JTextArea over JLabel(image for background) Can't Receive Mouse Events

    Hi, I use JLabel for putting background image to a JWindow. But when i put a JTextArea component, i can see and edit the contents but JtextArea only receives keyboard events. When i click on it ,its Focus Gained Event is not fired. No blinking cursor is shown.
    I tried to use JLayeredPane and put them on different layers but it doesn't solve the problem.
    I searched the Forums but can't find a suitable answer.
    Any comments please...

    hey man,
    your problem happen not because your JTextArea over a JLabel, but cause JWindow not take focuse before jdk1.4, so if you need to see your blinking cursor just replace your JWindow with a JFrame.
    for the JTExtArea focusing problem, u may refer to the sun bug forum there is a lot of work around.

  • Can't capture key event in applet

    Hi,
    Currently i'm developing an applet. However, i fail to capture the key event in the applet. The key that i fail to capture is VK_TAB. Any idea to handle this?
    Thanks in advance!

    to capture key event, u need to
    1. addKeyListener
    2. focus on that component (yourApplet must focusable)

  • Need key events in JPanel

    I can't receive key events in a JPanel, and need to figure out how. While the JDialog I added my JPanel to originally could catch these, once I added more components (like a JTextBox and JCheckBox), neither my panel nor dialog caught any key events at all. Isn't there some way when my panel has focus to capture and respond to key press events?
    Thanks,
    Mark McKay
    http://www.kitfox.com

    This works for a JFrame, didn't test it on a JDialog:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanelEvents extends JFrame
         public PanelEvents()
              JPanel main = new JPanel();
              main.setPreferredSize( new Dimension(300, 300) );
              main.setFocusable(true);
              getContentPane().add( main );
              main.addMouseListener( new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        e.getComponent().requestFocusInWindow();
                        System.out.println(e.getPoint());
              main.addKeyListener( new KeyAdapter()
                   public void keyTyped(KeyEvent e)
                        System.out.println(e.getKeyChar());
              getContentPane().add(new JTextField(), BorderLayout.NORTH);
         public static void main(String[] args)
              JFrame frame = new PanelEvents();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • 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.

  • Javafx multiple key events

    I have created a program in which a scene have two objects, and each object reacts when certain key is pressed, for example, when 1 is pressed , object 1 prints it's state,a and when 2 is pressed object 2 reports its state, but the program only work for object which is declared first in the scene
    following is an illustration
    import javafx.scene.input.KeyEvent;
    import javafx.scene.Scene;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    * @author Vaibhav
    Stage{
        scene: Scene{
            content: [
                Rectangle{
                    onKeyPressed: function(ex:KeyEvent):Void{
                        println('first rectangle');
                Rectangle{
                    onKeyPressed: function(ex:KeyEvent):Void{
                        println('Second rectangle');
    }but it prints only for fist rectangle , is there a workaround

    Only the object, which has the focus, can react on key events. Apparently in your case the first object has the focus, therefore the second one does not receive the events. You can set the focus manually with requestFocus().

  • 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.

  • 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

  • How to catch key events

    Hello!
    I have a component which extends JPanel. Now I dynamically add a JTextField as a child to this component. The problem is: when the textfield has focus, how can I get key events in my panel before the textfield gets them (and maybe intercept them so that the textfield doesn't get them at all)?
    Background: the component is a self written table and the textfield is an editor. Now I have to make sure that when I am editing and press e.g. "cursor up", that not the textfield will get this key event but the table (which should traverse the current cell then ...)
    The problem is: I cannot change the textfield (extend it or something) because a possible solution has to work with any java awt "Component" (or at least with JComponent).
    Any help very appreciated.
    Michael

    Hello,
    implement the keyListener interface for the Extended component...
    and in Keypressed method
    keyPressed(keyEvent){
    // do all ur reuirements here
    //and comsume the keyEvent...
    hope this helps

  • 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.

  • Key events in a form

    Hello!
    Maybe I'm missing it, but how can one catch key events on a form?

    One way is to create a CustomItem and add this method:
    protected void keyPressed(int key) {
        System.out.println("Key pressed: "+key);
    }This will print the value of the key pressed when the CustomItem is focused.

  • How to listen a key event without having any window component

    Hi all,
    I would like to know how can I listen key events from an application that doesn't use windows
    Thanks

    yoiu can make a Thread run inside your application. This will listen for inputs in the command line. For examplethis is part of a chat server (on the console) with let the server manager to enter messages or commands.
    The message or command entered on the console by the user is catched and processed as a String. The string is passed to the processConsole() method, you must define yourself.
    Th Thread is never stopped, so the user may enter any message at any time
    The core of you application should also be a Thread for better performance, but maybe it will also work without. Jst try and provide needed importstatements.
    Runnable runInput = new Runnable() {
            public void run() {
              while(true) {
                try {
                  byte buffer[] = new byte[255];
                  System.out.print(prompt);
                  System.in.read(buffer);//, 0, 255);
                  String inputString = new String(buffer, "Default");
                  processConsole(inputString);
                catch(NullPointerException npe) {
                  System.out.println("Syntax error");
                catch(Exception e) {e.printStackTrace(); }
          Thread inputThread = new Thread(runInput);
          inputThread.start();

  • If the table cell can not receive a virtual key?

    Hello,
    Want to execuate a "copy/paste" function in the table control. I hope type the "Ctrl+c" to copy  text in a cell, but nothing to do with the "ctrl" key pressed.
    David

    Table can receive and trap Ctrl + someCharacter in keypress event: you can discriminate the keys pressed with this code:
    if (event == EVENT_KEYPRESS) {
    if (GetKeyPressEventModifiers (eventData2) == VAL_MENUKEY_MODIFIER) {
    sprintf (msg, "Ctrl + %c pressed.", GetKeyPressEventCharacter (eventData2));
    MessagePopup ("Notice", msg);
    else if (event == EVENT_VAL_CHANGED)
    MessagePopup ("Notice", "Cell value changed.");
    Unfortunately, if the table is in edit mode Ctrl-C and Ctrl+V appear to be trapped by the system at low level and not to be passed to the control callback. Within CVI you can trap EVENT_VAL_CHANGED event, but I see no way to discriminate between a user type-in and a paste operation except for trapping whether a previous keypress event was received, which can be a troubled way to go. I can't see a way to trap Ctrl+C.
    There may be a method to get those event using some windows API but I don't know it.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

Maybe you are looking for

  • Why can't I add Birthdays in iCal unless they come from Address Book !

    I don't get it. I have a Birthdays calendar that seems to only allow birthdays to be created from the Address Book. If I go to iCal, and select the Birthdays calendar and then try to double click on a date, I just get the message that reads; "Read On

  • Problem with Order PP orders

    hi all Das anybody knows some Fuba ( Call funktion) for PP-Orders . I have to design an interface for Netplans. Thanks for your help chris

  • MIFI 4510l speed issue

    Mfif 4510L 4G LTE speed has deterioated to .25 to .40mbps from 1.5 to high of 6.2mbps. anyone else experiencing this issue. I've done battery pull, sim removal with no positive results. filed a trouble ticket with support but no response to date. I h

  • F4 functionality on selection screen

    Hi, i am having One requirement that  need to create f4 functionality on selection screen. please give me solution on that

  • ECCS Flexible upload dump GETWA_NOT_ASSIGNED

    Hi gurus! I'm trying to upload some financial statements for the ECCS module using transaction CXCD (Data monitor). When i double clic the company to upload the data, using the corresponding method, it returns a dump with a GETWA_NOT_ASSIGNED message