Associating key events to a TextBox

Hello All!
Can anybody tell me how to associate key events with a TextBox? Something like when a certain key is pressed and released, a certain combinations of characters is inserted e.g. =-)
I am trying to develop a simple application that allows users to type text with non-English characters, e.g. Russian and for that I have created a canvas and I am using key events i.e. KeyPressed and KeyReleased methods. Using a canvas is a bit insufficient because users cannot move the cursor freely through the text.
I have read on te web that I can create a CustomeItem and override the KeyPressed methods but I could not do it; I could not find any simlar code example.
Can anybody help me by providing me with a simple example or suggesting me an alternative way?
Many thanks in advance

{color:#008080}*Hello again!*
I managed to create a CustomItem that overrides KeyPressed method, but now I am having difficulties making my textBox reacts to my keyPressed method.
The early version of this CustomeItem overrides the KeyPressed method by assigning each key to a certain collection of chars. When a key is pressed, a string of these chars is drawn on the Canvas, which works fine. Now because I want to be able to edit the text, e.g. delete a certain char in the middle of the string, I want to use a TextBox or a TextField. The current problem is that my TextBox does not react to my key presses the way I want (I used setString() method); it reacts to the original key presses which print the original chars (from A through to Z and 1 through to 9).
Is it possible to set the contents of a TextBox or TextField depending on my key presses? Could you suggest me an alternative way?
Many thanks in advance!!{color}

Similar Messages

  • How to consume key events

    I would like to create a subclass of TextBox that only allows numeric input. My idea was to provide my own onKeyType() handler and consume any key events that do not correspond to digits. However, I can't find any way to consume key events from further processing. How do I do this?
    Are there any other suggestions how to accomplish the task of providing your own filter concerning valid key input?
    /Bengt

    I also wanted a kind of validators for the TextBox class of JavaFX. So I've tried solving the problem using the SwingTextField class and some Java APIs. The following is my code for a SwingTextField accepting only digits, but I do want it to be much simpler.
    import java.awt.AWTEvent;
    import java.awt.event.AWTEventListener;
    import java.awt.event.KeyEvent;
    import java.awt.Toolkit;
    import javafx.ext.swing.SwingTextField;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javax.swing.JComponent;
    class DigitKeyEventHookListener extends AWTEventListener {
        public-init var  source:JComponent;
        public  override function  eventDispatched( event:AWTEvent):Void {
            if (event.getSource().equals(source)) {
                var keyEvent : KeyEvent = event as KeyEvent;
                var keyCharacter = keyEvent.getKeyChar();
                var isDigit = false;
                var code = keyEvent.getKeyCode();
               if ((KeyEvent.VK_0 <= keyCharacter) and (keyCharacter <= KeyEvent.VK_9)) {
                       isDigit = true;
                if ((code ==KeyEvent.VK_DELETE) or (code ==KeyEvent.VK_BACK_SPACE)) {
                    isDigit = true;
                if ((code ==KeyEvent.VK_LEFT) or (code ==KeyEvent.VK_RIGHT)) {
                    isDigit = true;
               if (not isDigit) {
                    keyEvent.consume();
    function createSwingTextField() : SwingTextField{
        var field = SwingTextField {
            columns:12
        var listener =  DigitKeyEventHookListener{
            source: field.getJTextField()
        Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
        return field;
    Stage {
        title: "Digit Box"
        width: 200
        height: 80
        scene: Scene {
            content: createSwingTextField()
    }

  • Focus problem using key event

    Hi!
    There is an application I've created uses key event that needs your help.
    As you know, that setting 'Mnemonic' to a JButton object makes the button accessible by a key mentioned in the parameter as the following ->
                   OkButton.setMnemonic(KeyEvent.VK_O);Now, pressing 'Alt' and 'O' keys together will do the same action as the 'OKButton' does.
    But as of me, I think pressing two keys together is not a complete handy job.
    So, is there any code that will do the same, by pressing only the 'O' key ?
    Ok! I know that there is something to be taken care of; that is, if I want the button to react by pressing only the 'O' key the button must be in focus [value returned by the method [code]isFocusable() for the button must return true.]
    Then how the 'Mnemonic' works ?!! When 'Mnemonic' do something, button does not have any focus.
    Only, I press the Alt+O and the work done successfully! No need to take care wherever the focus is. So, is there any way to do alike, where I don't have to manage the focus subsystem?? I would only press the 'O' key and the task will be done.
    Please send a sample code. Thanks!

    I suggest you look into Key Bindings:
    "How to Use Key Bindings"
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    Here is a short demo program that uses Key Bindings to do what you describe:
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    public class PressOTest extends JFrame {
        public PressOTest() {
            super("Press O or C");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            // Action that will be associated with the OK button and with
            // the 'O' key event
            Action okAction = new AbstractAction("Ok") {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(PressOTest.this, "Ok!");
            // Action that will be associated with the Cancel button and with
            // the 'C' key event
            Action cancelAction = new AbstractAction("Cancel") {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(PressOTest.this, "Cancel!");
            // Register Key Bindings for the 'O' and 'C' keys:
            InputMap im = getRootPane().getInputMap(
                    JComponent.WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getRootPane().getActionMap();
            im.put(KeyStroke.getKeyStroke( KeyEvent.VK_O, 0 ), "ok");
            am.put( "ok", okAction );
            im.put(KeyStroke.getKeyStroke( KeyEvent.VK_C, 0 ), "cancel");
            am.put( "cancel", cancelAction );
            // Create and add OK & Cancel buttons:
            JButton okButton = new JButton(okAction);
            JButton cancelButton = new JButton(cancelAction);
            Box box = Box.createHorizontalBox();
            box.add( Box.createHorizontalGlue() );
            box.add( okButton );
            box.add( Box.createHorizontalStrut(10) );
            box.add( cancelButton );
            box.add( Box.createHorizontalGlue() );
            getContentPane().add( box );
            setSize(300, 300);
            setLocationRelativeTo(null);
        public static void main(String[] args) {
            new PressOTest().setVisible(true);
    }

  • On Key Event change sprite and sound

    I can't sort this out for the life of me.
    I have this at the moment....They are cast member scripts.
    There are four movies that switch on mouse clicks along with
    their associated sound.
    Trouble is that they are different sizes and the largest
    stays on the screen behind the new clip.
    I tried an unload
    _movie.unLoadMember(member("movieTwo"))
    but wherever I put it it did not work.
    I am new to Director and using ver11
    I have put the first clip on channel 1 and its sound on sound
    channel 1. Then that has a cast memeber script to swap the sound
    and image from the cast.. Each clip has a cast member script to
    move to the next clip.
    I did post earlier in the 'basics' a similar problem but have
    as yet found no solution.
    I really do need to have the changing of clips and of sound
    driven by key events. But I cannot get any key
    event to be recognised by director when the projector runs..
    Where does one put key.up and key.down in director?
    I really am stuck here and truly any help would be great
    Cheers

    You can place 'on keyUp' or 'on keyDown' event handlers on
    any sprites
    that would normally get keyboard input (i.e. editable #text
    or #field
    sprites as well as certain #flashComponents). You can also
    make a
    "movie-wide" control by putting an 'on MouseUp'handler in a
    MOVIE
    script. This event will happen if there is no editable text
    item on the
    stage.
    If you want to use a global keyDown handler, you need to set
    up 'the
    keyDownScript' (refer to the help file for explanation and
    syntax)

  • Macbook misses some key events for a few seconds

    I have noticed that for last two months or so something strange happens to my Retina MBP. Once in a couple of days it stops responding to some key events. It is like it handles only one keypress out of 4-5. Nothing seems to be wrong with the keyboard and it is not about a particular key or keys. And about 10-15 seconds later everything goes back to normal. I do not see any suspicious messages in the logs, the computer is connected to the power supply...It happens just by itself in the middle of the day, when I am typing.
    Almost looks like some interrupts get lost by the system while it is busy with something else. But I have checked the load level and running processes - nothing interesting there....And whatever it is - it happens during a very short period of time.

    Hi,
    No, I have not returned my MBP yet. In fact, I would rather avoid doing this unless I am convinced if it is a hardware issue. And I do believe it is not. Just recently I have spent some time investigating it and I have found very stroing correlation between the moments when this happens and these messages in the kernel log:
    Jan 13 10:49:54 mbp-wifi kernel[0]: Sandbox: sandboxd(96471) deny mach-lookup com.apple.coresymbolicationd
    Jan 13 10:54:31 mbp-wifi kernel[0]: Sandbox: sandboxd(96499) deny mach-lookup com.apple.coresymbolicationd
    Jan 13 10:54:31 mbp-wifi.home sandboxd[96499] ([96497]): mdworker(96497) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:54:31 mbp-wifi.home sandboxd[96499] ([96498]): mdworker(96498) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:56:32 mbp-wifi.home sandboxd[96504] ([96503]): mdworker(96503) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:56:32 mbp-wifi.home sandboxd[96504] ([96502]): mdworker(96502) deny mach-lookup com.apple.ls.boxd
    And I have also noticed that my Spotlight database gets reconstructed too often, which means it gets corrupted.
    From all this I conclude that it is most likely the software issue and it seems to be linked to spotlight. I saw people reporting similar things. So now I am researching on how to fix it without disabling the spotlight.
    In general, I believe that the quality of Apple software is going down, it is not like 4-5 years ago And Apple does seem to care less and less about it.
    If in your case it happens all the time, not just once in a while, and you see that a particular key has problems - it is possible that we are talking about the different issues and yours might be really about the keyboard.

  • 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

  • Catching key events in application

    I have a JFrame with a JDesktop containing lots of JInternalFrame with various of components such as JTextFields etc.
    Now, i want to have a "main" listener that will catch key events no matter which component that has focus. For example pressing CTRL+A should produce something in the application no matter which component that has focus.
    How do I implement this in an easy way?

    It doesnt seem to work to add a KeyListener to the JFrame...
    this.addKeyListener(new KeyAdapter(){
                   public void keyTyped(KeyEvent e){
                        System.out.println("KeyTyped()");
                   public void keyPressed(KeyEvent e){
                        System.out.println("KeyTyped()");
              });Adding that to the JFrame gives nothing to System.out when a JTextArea inside an JInternalFrame has focus.

  • Object Movement with Key Events

    Hi everybody!
    Im trying to move an object over the screen with keyboard buttons. The problem I have come across with is that I would like to use the right button to move right, up button to move forward, etc. but I cant push, for example, right and up buttons at the same time to make a diagonal movement. How can I solve this?
    Thank you and regards.

    I added key events to a sequence and than check them in the program.
    Something like this:
    class Car extends CustomNode {
        var keys:KeyCode[];
        public override function create(): Node {
            ImageView {
                transforms: [ Translate{ x: bind x, y: bind y }, Rotate{ angle: bind direction}]
                x: -w
                y: -h
                image: Image { url: "{__DIR__}car.png"}
                onKeyPressed: function( e: KeyEvent ) {
                    insert e.code into keys;
                    if(e.code == KeyCode.VK_UP){
                        ds = 2.0;
                    }else if(e.code == KeyCode.VK_DOWN){
                        ds = -2.0;
                    }else if(e.code == KeyCode.VK_LEFT){
                        da = -1.0;
                    }else if(e.code == KeyCode.VK_RIGHT){
                        da = 1.0;
                onKeyReleased: function( e: KeyEvent ) {
                    delete e.code from keys;
        public function move(){
              // check keys
    }

  • KEY events in MIDlets

    Hello all,
    I am basically new to J2ME MIDP development and also new to this
    forum. So apologies if this has already been covered or turns out to
    be a stupid question :) Here goes:
    I am trying to develop a MIDlet where I have a Form to accept certain
    values from the user. This is fairly straightforward and is easy to
    create with the high level Form a and TextField objects.
    Now, I wish to add a functionality to my MIDlet, in which, the user
    can press a specific key.. say the "Select" key or the "Call" key.. at
    any time during the form to start another thread of operation which
    performs something totally different... say for example, the user is
    entering values into the form and in between somewhere he presses this
    specific key and the phone start playing music. I hope you get my
    point.
    Basically I want to listen for key pressed or key held events on a
    Form object. Now I understand that Key events can be found only on the
    low-level Canvas based UIs. So is it possible to do it with Screen class
    elements..?
    Thanks,
    Nik

    You can try to use a CustomItem. What events will be delivered to the custom item depends on the implementation, though. Also these events will be only delivered when the CustomItem is focused.
    Have a look at the J2ME Polish GUI for using CustomItems for MIDP/1.0 devices as well.
    http://www.j2mepolish.org
    Best regards,
    Robert

  • Binding Mouse and Key Events.

    Hi,
    When a user clicks the Ctrl + V the data from the clipboard
    is pasted into the user area. Instead of using this can we do it
    using a mouse click. For now, I am planning to bind the event code
    of these combinations (CTRL + V == 86) to the mouse click. But when
    I tried this I am unable to bind this key event to the mouse event.
    Can anyone help me out for getting out of this problem.
    Regards,
    eodC.

    No, it isn't.
    Kind regards,
      Levi

  • 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

  • 2nd JFrame at Full Screen not registering key events

    I've written an application that launches other applications distributed as JARs with a particular method (replacing the main method). These other applications run at full screen.
    Whilst I have got these other applications to work in that they display correctly and do everything else, I require them to register key events. If I run these applications on their own (i.e. having not been launched by the primary application) then the key events are processed correctly. However when they are launched from the primary application the key events are not registered.
    I have tried requesting focus from the full screen JFrame but it doesn't seem to be able to.
    Any ideas?

    Possible that the keystrokes are really being trapped by the other gui, which stops registering them when it's not visible.
    IF that's the case, you'll need to re-design your keyboard trap as part of the second JFrame, wholly independent of the original JFrame or originating app. Also, it may be thread-starved i.e. operating off the originating program, which thread may be stopping when it has no focus.
    That's all the ideas I have.

  • Is using key events really that hard?

    I am trying to implement a keyListener for my application, and it seems
    way harder than it should be. My application is simple: A JFrame
    with one button and one JPanel upon which I draw. When I click
    in the JPanel and type, I want things to happen.
    After much looking, it seems I have to not only implement KeyListener,
    but also MouseListener, so when the mouse enters I can call
    requestFocusInWindow().
    That seems to work sometimes, but not when I leave and come back,
    and not always when the application first appears.
    So do I also have to implement FocusListener?
    Why is this so hard to do? MouseListener is very easy to implement,
    but KeyListener seems to be a huge pain in the butt.
    Can someone point me to a simple tutorial or example that just
    has a few swing elements, and processes key events?
    I feel like with Java I often try enough things until it finally works,
    and never really understand why, and what it was that fixed it.
    The documentation and API does not fully describe everything one
    needs to know to use the API "properly". Am I the only one frustrated
    by this? I have programmed in Java/Swing for years, and JUST LAST
    WEEK discovered that when implementing paint in swing, one should
    override paintComponent and not paint. But then why does overriding
    paint usually work? There are too many quirks in Java that let you
    get away with doing things wrong, and then suddenly, your application
    is broken. It wouldn't be so bad if the API was more clear on some of
    these suble issues.
    Thanks,
    Chuck.

    How to Use Key Bindings

  • Lag on key press (key event)

    Hello, I am currently working on a simple game in Java. I've used Java's Key_Pressed in Key Event to control a ship moving back and forth with the up and down keys. I've noticed that when a key is pressed there is a short pause before the ship actually moves. What can I do to avoid this pause?

    The "repeat rate" for holding a key down is controlled by the OS.
    You should not be relying on multiple KeyEvents to move your component as the repeat rate will vary from machine to machine. Actually you should not be using KeyEvents anyway you should be using [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]Key Bindings
    On keyPressed binding you would start a Timer and then on keyReleased you stop the Timer. You can then control the interval at which the Timer fires so you game will be consistent on all machines.

  • Plz  tell me motrola support repeated key events.

    Plz tell me about my this ancient problem that if some device support repeated key event than tell me its name and also provide a link to download it.
    moreover also tell me about this strange content type:-
    Here i have content type which is strange for me :- response.setRequestProperty("Content-Type","application/x-www-form-urlencoded") plz tell me either it will ok if i want to display some other language;
    i want internationalization and want to set utf-8 but now tell me for what purpose is above content type and what would be its alternative. thanx

    See http://www.kobjects.org/devicedb/ for which devices do and don't support key repeat events.
    Application/x-www-form-urlencoded is defined at
    http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
    You can use application/x-www-form-urlencoded with UTF-8 provided that the server is expecting UTF-8 encoded bytes. However, I don't think many MIDP implementations support String.getBytes("UTF-8") so you may be stuck with doing the UTF-8 encoding yourself.
    If you control the server, you may want to instead use DataOutput.writeUTF() from the client and DataInput.readUTF() from the server. Another alternative is to use XML, where you can employ character references for non-US-ASCII characters.

Maybe you are looking for

  • 2nd gen iPod touch YouTube app can't search YouTube

    2nd gen iPod touch can't search YouTube through the YouTube app. I'd really appreciate some help in resolving this problem.

  • I can't download Photoshop CS2 on MacBook Air running Mac OS X

    So yeah, i've got troubles downloading Photoshop CS2. It's free, i belive. I have MacBook Air, and it just dont work. Idk what to do.

  • Ugh. what to do? help!

    i updated to the new ios4 and now all my apps either crash or freeze. the phone is super sluggish. can i just go back to ios3 or is there a way to fix this? i just got my phone may 19 and it is brand new! i dont have to have the few changes offered i

  • Role of slapd on linux SRSS servers/misconfiguration of slapd?

    Recently one of our failover SRSS4 servers (running on OpenSuSE 10.3) ended up having a catastrophic hardware failure necessitating rerolling a new one. In the past we have used a method for doing this that hasn't given us any problems. Basically we

  • Unavailable to FaceTime certain personS

    ive been trying to FaceTime this person and every time I try to it says unavailable to FaceTime. ive facetimed other people and it works fine and so have they done the same, but we just can't FaceTime each other. can anyone help at all? I don't know