Keyboard - Character replacement - Keystroke Event !

Hello ! I am developing a specialized editor using JEditorPane.
One the functionalities that I am trying to provide is character replacement using keyboard. Meaning that if some one enters, say, 'q' then a 'z' should be printed at the point of insertion. Something like
"This is a ebra"--> After typing 'q' on the keyboard before the beginning of the fourth word "ebra", the resulting text in the editor pane should look like "This is a zebra"; meaning here 'q' is used to type in 'z'.
Now here is my code but I am getting both 'z' and 'q' printed i.e. the result looks like, "This is a zebraq". So my questions are,
1) How do I get rid of the unwanted 'q'?
2) Is there a better way of doing this kind of replacement.
Thanks in advance!!
public void keyTyped (KeyEvent e)
PressedKey = e.getKeyChar();
String strBeforeInsert = new String("");
String strAfterInsert = new String("");
String docString = new String("");
try{
int length = edit.getDocument().getLength();
strBeforeInsert = edit.getDocument().getText(0,dot);
System.out.println("---- strBeforeInsert " + strBeforeInsert);
strAfterInsert = edit.getDocument().getText((dot), (length-dot));
System.out.println("---- strAfterInsert " + strAfterInsert);     
catch (BadLocationException ble){
if (PressedKey == 'q')
     System.out.println(">>>>>> " + PressedKey);
     docString = strBeforeInsert.concat("z") + strAfterInsert;
     edit.setText(docString);

I would use a DocumentListener. Check out the Swing tutorial for more information:
http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html
In the insertString(..) method when a 'q' is typed, insert a 'z' instead.

Similar Messages

  • CharAt in a keystroke event using regular expression

    I'm working on a canadian postal code field.  I'm using a regular expression to validate the value.
    //accepts "A9A 9A9", "A9A9A9" or "" as valid entries excluding letters D, F, I, O, Q, U and W as well as Z as the first digit.
    var re = /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$|^$/i;
    if(re.test(event.value) == false){
    app.alert("Code postal invalide", 0, 0,"CODE POSTAL");
    event.value = "";
    I also added a keystroke event to prescan every digit and toUpperCase() them.
    //accepts letters, numbers, backspace or spaces
    var re = /[ABCEGHJKLMNPRSTVWXYZ]|\d|^$|\s/i;
    if (!event.willCommit){
    if(re.test(event.change) == false){
      event.rc = false;
    else{
      event.change = event.change.toUpperCase();
    I want to Replicate the behavior of an arbitrary mask where I can force a character to appear at a specific position.  In this example, instead of letting the user decide wether he adds a "space" or not between the two parts of the code, I want to:
    1-Remove "\s" in the keystroke regexp so the user cannot use "space";
    2-Replace "( )?" for "( )" in the validation regexp;
    3-Force a space at charAt(3).
    Is it possible to have it appear while the user is still typing or is my only option to change the value once committed or as a cutom format script?
    In the same manner, is it possible to specify a different regexp keystroke depending on the position of each character?
    charAt(0), charAt(2), charAt(5) would be letters
    charAt(1), charAt(6), charAt(7), would be numbers
    charAt(3), would automatically add a "space"
    in the end, I want the same behavior as an arbitrary mask without the annoying alert when entering a wrong digit.

    The entire string validation is different from the keystroke validation. The keystroke validation can check each keystroke as it is typed while the string validation can only process the entire string at one time.
    You need to break your RegExp to describe the requirement for each character. You can even specify the possible number of repetitions of the pattern.
    A discussion on to create keystroke validations would be far too long for a post in a forum.
    Acuumnen has an ebook about Acrobat forms and has a couple of chapters to some simple validation and formatting scripts.

  • ABAP Webdynpro: Capturing keystroke event

    Hello,
    There is a potential requirement to capture a keystroke event from a SAP standard webdynpro text box and provide a character count in a custom UI display text box on number of characters remaining.
    From initial research - it looks like this may be possible with Unified Rendering Light Speed in WebDynpro ABAP?
    http://help.sap.com/SAPhelp_nw73/helpdata/en/74/0beccf62a7425ab9e1b2077fa1bc6e/frameset.htm
    If it is possible, how exactly would it be implemented.  (Which event / action would be used?) 
    It appears this can be activated and used on existing SAP standard webdynpros? 
    Thank You,
    Mike

    try something like this...
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s;
    s = br.readLine();
    if(s.equals("R")){
    if(s.equals("R")){
    you also can use s.equalsIgnoreCase("R") if u dont care if its capital or not

  • Xslt sample for entities to keyboard character

    We need the xslt sample for entities replacement text. For instance I have to convert the entities ‘(’  to keyboard character ‘(’.

    Hi,
    Here's a very simple one... If the param1 matches with any value in the input it will return true...
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:param name="param1"/>
      <xsl:template match="/">
      <xsl:value-of select=".//*/text() = $param1"/>
      </xsl:template>
    </xsl:stylesheet>
    Cheers,
    Vlad

  • Read in a single keyboard character

    Could someone help me with the following?
    Read in a single keyboard character and display an appropriate message depending on whether it was a letter, a digit or some other type of character. Use a nested else-if statement.
    I would appreciate it, thanks.

    objJTextField.addKeyListener(new KeyboardEvent());
    class KeyboardEvent extends KeyAdapter{
    public void keyPressed(KeyEvent objKeyEvent){
              if (objKeyEvent.getKeyCode()!=KeyEvent.VK_BACK_SPACE)){
                   System.out.println("You make a click on Back Space");
    }

  • Non Keyboard character.

    Hi all,
    I web host a folder of files in the apache. There a file name which contains non keyboard character. I use URLENCODER, it been encoded to %E2%80%98. Sorry that i cannot passte the character here, as is a offline system.
    Although is being encoded, is still returns a 404 when try to access the files. Anyone met this issue before?
    By the way, what is the culture? Should i really allow all these non-keyboard character?
    Regards,
    becks

    becks wrote:
    URLencoder is java.Yeah I know.
    Just wondering how other people do it as well? I feel that should not let users copy paste those funny character into the system.Well it's not a very good system if it doesn't support Unicode. It's not that big an effort after all. Of course if you're not familiar with character encoding and unicode, I recommend you read this:
    http://www.joelonsoftware.com/articles/Unicode.html

  • Trying to use code found in working PDF from online in LC. (Keystroke Event)

    I found a PDF online (at http://www.planetpdf.com/developer/article.asp?ContentID=javascript_dynamic_updates_w) that works on my iPad running PDF Expert for iPad 5.0.4.
    I tried to recreate it in LiveCycle ES4 using the same code. However, the author says to place the code in the "keystroke" event. I can't find a "keystroke" event. I've tried it and variations in change, preOpen, and exit without any success.
    Can someone help me?
    This is the exact functionality I need and the only example that I have seen work in both a PC environment and an iPad (running PDF Expert).
    Thanks!
    Dan
    The code can be found at: http://www.planetpdf.com/developer/article.asp?ContentID=javascript_dynamic_updates_w
    The sample PDF can be found at: http://www.planetpdf.com/codecuts/pdfs/Populate.pdf
    I am specifically looking at the code in the dropdown box called "Three" - which is captioned as "Dynamic"
    Code follows:
    ==========
    /* This version updates a secondary combobox based on the entry
    ** selected by the user dynamically. The keystroke event should
    ** be processed until the value is about to be committed (as
    ** indicated by event.willCommit). */
    if (!event.willCommit) {
        var f = this.getField("Four");
        f.clearItems();
        /* In a keystroke event, event.change contains the non-export value of the item selected by the user. */
        switch (event.change) {
            case "Cities":
              ;       f.setItems(["Paris", "Berlin", "Amsterdam", "Rome"]);
            break;
            case "Fruit":
              ;       f.setItems(["Bananas", "Mangos", "Strawberries", "Papayas"]);
            break;
            case "Garden Tools":
              ;       f.setItems(["Hoe", "Rake", "Leaf blower", "Shovel"]);
            break;

    The first problem I see is that you are using an old version of WebUtil, which is not supported for use with Forms 10.1.2.3 and is probably the cause of the problem.
    RegisterWebUtil - Loading WebUtil Version 1.0.6
    The correct versions of frmwebutil.jar and webutil.pll are applied to Developer Suite installations and can be copied to Application Server. If you do not have an iDS installation, you can install the latest Forms Bundle patch which includes the correct WebUtil files. Refer to Patch ID 9593176 and Note 1188127.1. Be sure to review the ReadMe included with the patch.
    The second problem is that you are using Jinitiator. Jinitiator has been obsolete for a long time. However, if you have some reason why you must use it, I would recommend that you at least get the last version released (1.3.1.30). This can be downloaded from within MyOracleSupport (account required) using Patch ID 7410076. If you do not have access to MyOracleSupport and you are using Forms 10.1.2.3, then you can use JRE6 (1.6.0_37). Do not attempt to use JRE7
    http://www.oracle.com/technetwork/java/javase/downloads/jre6u37-downloads-1859589.html
    You would need to install the 32bit version: jre-6u37-windows-i586.exe
    References:
    <li>Note: 566628.1
    <li>Note: 561273.1

  • Cannot enable keyboard & character viewer

    After a fresh install of 10.7.5, I cannot enable the keyboard & character viewer. Neither the checkbox will stay checked, nor does the option appear in the input sources menu...
    Any ideas?
    Thanks,
    Klaus

    Thanks, Tom, for your speedy reply.
    This is what the Terminal commands produced:
    Last login: Sat May 11 21:33:45 on console
    You have mail.
    Macintosh-7:~ klausblume$ sudo rm /System/Library/Caches/com.apple.IntlDataCache*
    Password:
    Macintosh-7:~ klausblume$ sudo rm /var/folders/*/*/-Caches-/com.apple.IntlDataCache*
    rm: /var/folders/*/*/-Caches-/com.apple.IntlDataCache*: No such file or directory
    Macintosh-7:~ klausblume$
    No such file or directory
    As far as Onyx is concerned, the homepage is flogging MacKeeper (ugh). Is Onyx MacKeeper in disguise?

  • RTF non keyboard character missing

    When I export the RTF from the application file  non-keyboard character (symbol and mathematical pi fonts) converted in to square boxes.
    How to fix this issue.
    Please advice.

    becks wrote:
    URLencoder is java.Yeah I know.
    Just wondering how other people do it as well? I feel that should not let users copy paste those funny character into the system.Well it's not a very good system if it doesn't support Unicode. It's not that big an effort after all. Of course if you're not familiar with character encoding and unicode, I recommend you read this:
    http://www.joelonsoftware.com/articles/Unicode.html

  • How to detect keystroke events on the console

    I'm currently implementing a basic menu driven system which needs to
    identify keystroke events (eg. alpha characters). I'm not too sure of the
    best way to deal with this, but can anyone suggest how one could go
    about doing this?
    Cheers,
    Richie !

    If you are refering to the ability to capture user key strokes you will need to add a listener to the class. If is a matter of is it a charater or a number then look into isDigit. Or are you trying to capture Hot-Keys? Please specify and will see if we can help - Bart

  • Capturing keystroke event in console-mode

    Hi fellow Java Programmer
    I was stumbled upon what to be a simple question
    Is it possible to capture the keystroke event inside console-based application
    This is my scenario:
    I have a thread that is keep running for a predetermined amount of time,
    It is doing a background-sort-of-task. According to the requirement, it must be able to detect
    when the user press 'R' (which will trigger Reload) or when user press 'Q' (denoting Quit)
    I would appreciate if somebody come up with hint / snippet of source code
    regards,
    Honggo

    try something like this...
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s;
    s = br.readLine();
    if(s.equals("R")){
    if(s.equals("R")){
    you also can use s.equalsIgnoreCase("R") if u dont care if its capital or not

  • Keyboard character view list disappeared?

    Hey
    I recently update my mac os mountain lion ( not upgraded but just normal update from the app store ) and since then when I click on the country flag which is the language I don't see the keyboard character option to go to the list while before I was able to do it like to write arrows or something else
    so how can I retunr the option to the keyboard list?
    ty

    Go to the Language & Text system preferences and in the Input Sources tab check the option to enable these items as an input source to use (in the list to the left).

  • Keyboard character repeat delay

    I have JDK 5 Update 4. Does anybody have an idea on how to access the keyboard character repeat delay and repeat rate?
    I want to shorten the delay and possibly the repeat rate. Is there a way to get the keyboard and it's properties somehow?

    lol I delt with the same issue while making a galaxian clone.
    I wanted to completely get rid of the delay and make the repeat rate equal to as fast as java could execute it (meaning assume that it repeats every single time the paint() method gets executed).
    for instance, if I want the ship to move left and keep moving left (meaning no delay and incredibly fast repeat rate), I did this:
    inside my KeyListener I have boolean Left. inside keyPressed, I have a switch statement that, if the left key is pressed, sets Left to true. inside my paint() method, I check to see if myKeyListener.Left == true. if it does, I move my ship to the left. inside of keyReleased I have a switch that sets Left to false. therefore, there is no delay at all between the key being pressed and the ship moving, and so long as you hold the key down, the ship keeps moving over at a constant rate that has absolutely nothing to do with the repeat rate of the KeyListener. hacking into the OS is way unnecessary.
    if you want there to be a significant delay (the way my firing of bullets does), then do this
    //inside the constructor of your GUI, set long milliSec to System.currentTimeMillis().
    if (MyKeyListener.SpaceBarIsPressed == true && System.currentTimeMillis() >= 500+milliSec)
         //the code necessary to shoot a bullet
         milliSec = System.currentTimeMillis()
    }that will make it so the next bullet cannot be fired until its been at least 500 milliseconds since the last bullet was fired. giving you a constant repeat rate with no start delay.

  • Show Keyboard & Character Viewers setting not working

    I like to have access to the Keyboard and Character Viewers in the menu bar; however, the setting on my new MacBook does not work. I have checked the "Show Keyboard & Character Viewers in menu bar" many times and it unchecks itself as soon as I leave the Keyboard tab of the Keyboard setttings in System Preferences.
    Could a preference file be corrupted? (I migrated data from my old MacBook (OS 10.7) to my new MacBook (10.9). Perhaps this has something to do with the problem?)
    Or, is there a command line way to show the preference that might stick better than the checkbox in the System Preferences?
    Any insights would be appreciated.
    Thanks,
    -Robert.

    BikerBob wrote:
    The Input Sources menu has to be enabled to show the Keyboard & Character Views menu, which appears under the Input Sources menu. This was not the case in Mac OS 10.7, which I was previously using.
    However, it is odd that the Keyboard & Character Views option is not greyed out in the Keyboard tab when the Input Sources menu is not enabled.
    Indeed, the way Apple has done this in Mavericks seems both odd and cumbersome.   I think it would be worth telling them so at
    http://www.apple.com/feedback
    The official instructions assume you have already enabled the input sources menu:
    http://support.apple.com/kb/PH13746

  • Geometry angle symbol, can it be typed? which font or keyboard character?

    How do I type the angle symbol   /_  (roughly) on a Mac? Is it a font I need or a keyboard character?

    In the app you are in click on the space where you want the charter then click the edit menu then select special characters then select math in the left of the window the find the symbol and click on it to insert.  http://docs.info.apple.com/article.html?path=Mac/10.4/en/mh1064.html

Maybe you are looking for