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()
}

Similar Messages

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

  • How to generate key events to a componet without keyboard

    I want to generate a key event, a Keylistener is already there, (in fact, java3D's KeyNavigatorBehavior). I want to use other input methods instead of key pressings, so how I generate the key event manually
    thx,

    Look at java.awt.Robot. It has a keyPress() method to simulate key presses.

  • 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 catch key events in JWindow???

    Can somebody please suggest me how do I catch key events in a JWindow. I tried without success with addKeyListener( ) method. My sample code is attached below. I've j2sdk1.4.2_03 in my PC.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class EventCatcher extends JWindow implements KeyListener {
         public EventCatcher() {
              super();
              Container c = getContentPane();
              setBounds(100,100,400,400);
              c.setLayout(new FlowLayout());
              JButton button = new JButton("Hello");
              c.add(button);
    addKeyListener(this);
    requestFocus();
    setVisible(true);
         public void keyReleased(KeyEvent ke) {
    System.out.println("**************");
         public void keyPressed(KeyEvent ke) {}
         public void keyTyped(KeyEvent ke) {}
         public static void main(String str[]) {
              new EventCatcher();
    Regards,
    Koushik

    Hi GraemeHook!
    This is Khurram. I tried your code on my problem that is 95% like this problem but it could not be solved.
    can u please take view on my code.
    I m trying to move a frame that extends from JWindow on runtime with Key Board Arrow keys. but this only works when I extend this MainApp class from JFrame, but not when from JWindow.
    can u please help me. I also posted my own topic but no one response so found it resambling to my problem.
    hoping to hear from u soon
    you can also tell me at my email address
    [email protected]
    thanks
    ===========================================================
    MainApp.java
    *MainApp.java
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class MainApp extends JWindow {
      static LocationManager appLoc = new LocationManager();
      public MainApp() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String[] args) {
       MainApp frm = new MainApp();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            int width = screenSize.width;
            int height = 45;
              frm.setFocusableWindowState(true);
            frm.setFocusable(true);
            frm.setSize(width, height);
            frm.setLocation(appLoc.setAppAtBottomCentered(width, height));
            frm.setLocation(appLoc.moveAppUpward(100));
            frm.setVisible(true);
      private void jbInit() throws Exception {
        this.getContentPane().setBackground(Color.white);
         addKeyListener(new java.awt.event.KeyAdapter(){
          int moveSpeed = 4;//must be even
          public void keyPressed(KeyEvent e){
            //JOptionPane.showMessageDialog(null,""+e.getKeyCode());
             if(e.getKeyCode() == KeyEvent.VK_SHIFT)
              if(moveSpeed==4)
                moveSpeed = 12;
              else
                moveSpeed = 4;
            if(e.getKeyCode() == KeyEvent.VK_UP)
              setLocation(appLoc.moveAppUpward(moveSpeed));
            else if(e.getKeyCode() == KeyEvent.VK_DOWN)
              setLocation(appLoc.moveAppDownward(moveSpeed));
            else if(e.getKeyCode() == KeyEvent.VK_LEFT)
              setLocation(appLoc.moveAppToLeft(moveSpeed));
            else if(e.getKeyCode() == KeyEvent.VK_RIGHT)
              setLocation(appLoc.moveAppToRight(moveSpeed));
            else if(e.getKeyCode() == 107) {//NUMPAD '+' Key For Vertically Increasing
              setSize(appLoc.increaseSize(0,moveSpeed));
              setLocation(appLoc.updateLocation());
            else if(e.getKeyCode() == 109) {//NUMPAD '-' Key For Vertically Decreasing
              setSize(appLoc.decreaseSize(0,moveSpeed));
              setLocation(appLoc.updateLocation());
            else if(e.getKeyCode() == 61) {// '+' Key For Horizontal Increasing
              setSize(appLoc.increaseSize(moveSpeed,0));
              setLocation(appLoc.updateLocation());
            else if(e.getKeyCode() == 45) {// '-' Key For Horizontal Decreasing
              setSize(appLoc.decreaseSize(moveSpeed,0));
              setLocation(appLoc.updateLocation());
    }====================================================================
    LocationManager.java
    * LocationManager.java
        import java.awt.*;
        import java.awt.event.*;
        import javax.swing.*;
        import java.util.*;
        import java.sql.*;
    public class LocationManager {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        static Point newPoint = new Point();
        static Dimension newDim = new Dimension();
        static Dimension minDim = new Dimension();
        /** Creates a new instance of LocationManager */
        public LocationManager() {
        public LocationManager(int width, int height){
            this.setAppCenteredWithDim(width, height);
        public Point setAppCenteredWithDim(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width)/2;
            newPoint.y = (sHeight-height)/2;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtTopCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width)/2;
            newPoint.y = 0;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtBottomCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width)/2;
            newPoint.y = (sHeight-height);
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtRightCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = 0;
            newPoint.y = (sHeight-height)/2;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point setAppAtLeftCentered(int width, int height){
            //Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          newDim.width = width;
          newDim.height = height;
            int sWidth = screenSize.width;
            int sHeight = screenSize.height;
            newPoint.x = (sWidth-width);
            newPoint.y = (sHeight-height)/2;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppUpward(int step){
            newPoint.y -= step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppDownward(int step){
            newPoint.y += step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppToLeft(int step){
            newPoint.x -= step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Point moveAppToRight(int step){
            newPoint.x += step;
            return newPoint;
            //return new Point(this.x, this.y);
        public Dimension increaseSize(int w, int h){
          minDim.width = 116;
          minDim.height = 56;
          newDim.width += w;
          newDim.height +=h;
          if(w==0 && newDim.height > minDim.height)
            newPoint.y -= h/2;
          else if(newDim.width > minDim.width )
            newPoint.x -= w/2;
          return newDim;
        public Dimension decreaseSize(int w, int h){
          minDim.width = 116;
          minDim.height = 56;
          if(newDim.width > minDim.width )
            newDim.width -= w;
          if(newDim.height > minDim.height)
            newDim.height -= h;
          if(w==0 && newDim.height > minDim.height)
            newPoint.y += h/2;
          else if(newDim.width > minDim.width)
            newPoint.x += w/2;
          return newDim;
        public Point updateLocation(){
          return newPoint;
            //return new Point(this.x, this.y);
    }===================================================================

  • How to consume ETW events data in C#

    Hi,
    I am using Microsoft.BizTalk.CAT.BestPractices.Framework for tracing data in Custom Pipeline Components, Maps and Orchestrations.
    I want to capture events data in Real-time by using C# code.
    Can someone help how can i capture events data in c#?
    Thanks,
    Shahzad

    Hi Shahzad,
    When you use the Microsoft BizTalk CAT Teams logging framework for instrumenting your BizTalk solution then
    it will write events to the Windows ETW sub system. You need to write a component,lets call it as a monitor that will capture these events and write to database. There is an excellent project in codeplex titled 'Testing inside BizTalk using ETW Tracing'.See
    here .
    It is basically a console app that detect events published to ETW by the BizTalk logging framework and then
    publish them onto an MSMQ queue .See the source code for this project and you can implement the same in your C# component.
    Regards,
    Sajith C P Nair
    Please mark as answer if this helps

  • How to handle key events in popup component

    Is there any possibility to handle keyboard events after a popup is opened
    requirement : I want to close popup when I press escape key (by default this functionality is present but in some scenarios this is not working ) so explicitly i want to handle key events for popup.
    Thanks,
    Raghavendra.

    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.

  • How to recieve key events

    Hi guys,
    in the javax.microedition-package i can't find something like the KeyListener in java.awt.event-package. How can I recieve the Key-char when the user is pressing a key?

    you will find this lisetener in canvas package not in form package

  • How to process key Events in a JTextArea?

    does anybody of you know how i can process KeyEvents in a JTextArea object? i know i can use the processKeyEvent-method but i don't want to process the Event on the current Caret-position - it would be cool to process this keyEvent at a given position anywhere in the text... it works if i set the CaretPosition to this special position, do the processKeyEvent-method and restore the Caret to it's original position but i want the user to be able to type at the same time as the KeyEvent on another place in the text is processed...
    sorry for my bad english (if it's that bad - i don't know :-) )
    greets and thanks,
    zeroconf

    I think i know one:-)
    Try to override insertString() method of your document.
    In fact create your subclass of the document.
    the insertString method has parameter offset. It's place in the document where changes should be done. All key type events are converted into the insertString() calls.
    So you can do like that
    class MyDocument extends DefaultStyledDocument {(or extends PlainDocument for JtextArea. it depends which component you use)
    public void insertString(int offset,String str,AttributeSet a) {
      int newOffset=getNewOffset(); //get real offset where you want to insert/remove content
      super.insertString(newOffset,str,a);
    JTextArea ta=new JtextArea();
    tc.setDocument(new MyDocuemnt()); //replace default document
    regards
    Stas

  • How to generate key events programmatically

    Hello friends,
    I am developing an application that would automaticall trigger some keboard events for this purpose i would like to trigger an event like alt+f4 i.e pressing alt+f4 together
    How can we do this using java
    regards
    hari

    You should be able to use the java.awt.Robot class to perform programmatic UI events.
    It doesn't seem that it permits use to do things like keyPress("alt-f4") so you might have to do something like this:
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_F4);
    robot.keyRelease(KeyEvent.VK_F4);
    robot.keyRelease(KeyEvent.VK_ALT);Hope this helps.

  • How to consume an event in windowClosing()

    Hi,
    I need to consume the window event once it has been serviced.
    class SymWindow extends java.awt.event.WindowAdapter
    public void windowClosing(WindowEvent event)
    // blah blah
    My_WindowClosing(event);
    My_WindowClosing(event) in turn pops up a JOptionDialog with YES, NO, CANCEL options. For YES, I can close this GUI by calling dispose(). But for NO, this windowClosing() gets called again, instead of closing this JOptionDialog. Also Close(x) for this JOptionDialog doesnt work ( windowClosing() gets called recursively again)
    My issue is that windowClosing() is being called recursively.
    So, what I want is that once this event has been serviced ( My_WindowClosing(event);), this windowClosing() should not be called again.
    Any suggestions please.
    Regards,
    Ashish

    Ashish, this forum is for Java-Collections,
    please post your question in appropriate places like AWT.

  • How to pass Key Event from command prompt to the java application

    If iam running a application that displays JFrame when i pressed CTR+C at the command prompt i.e console window please let me know how can it be passed to the JFrame ie application window

    I doubt that you can pass Ctrl+C to the application since the application is terminated by this key combination.
    You would try adding a WindowListener or may use a shutdown hook to capture the termination of the JVM.

  • How to send Remote controller key event

    Hi Sir,
    Can anyone tell me "how to send key event from "Remote
    Controller" to Flex application?
    for example. I want to control the Flash player or my Flex UI
    application from remote controller such as use firefly
    controller/streamzap controller/Gyration controller. Normally user
    will use mouse or keyboard to enter/generate event, now I want to
    use "Remote controller" to generate the key event. In Flex, how can
    I capture the key event from "remote controller"? Any sample code
    to provide that will be good.
    Thanks.
    Lin

    Here's a couple related threads
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=583877
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=712386
    I'd also suggest exploring the Search Forums available on the left,
    which is how I found those threads:
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=focus+traversal+tab+text&subCat=siteforumid%3Ajava57&site=dev&dftab=siteforumid%3Ajava57&chooseCat=javaall&col=developer-forums

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

  • Handling Key Event

    How to handle key events in the Console?
    Plz give sample code for it.
    Thanks in advance.

    Don't have any experience with it personally, but I think curses does this type of thing http://sourceforge.net/projects/javacurses/

Maybe you are looking for

  • How can I install Jam Packs on a new Mac Mini?

    I've a lovely new mac mini, but the little bugger has no disk drive.  I migrated several jam packs over from my old mac mini only to get a troubling error message requiring tht I reinstall the jam packs.  Alas, they refuse to be installed from a netw

  • OLE2_OBJECT AND DOCUMENT MANAGEMENT SYSTEM (DMS)

    Hi Experts. I'm trying to make a excel inform like a catalog with materials and images which are in a Document Management System. I'm using OLE2_OBJECT to make the inform in EXCEL, because I'm trying to do it with SMARTFORMS, and I cannot because I n

  • Is bad if i reset like 4 or 5 times my mac mini? Happen i just want to restore the lion but when i reset the mac me press always wrong in the keyboard

    I want to restore the program lion of my mac mini coz i want ti give my friend this. So i cheack the manual and say reset the computer and pres comado + R and i do that but me do wrong. Me no press good so i reset again. And i try again and finally m

  • XML gateway with multiple XML structures??

    Hi, I have a requirement to import data using XML gateway with different XML structures. Third party system sometimes will not provide certain tags itself if there is no data for the tag like contacts in below sample xmls. In that case we need to ign

  • Histogram behavior in CS6

    Hi, I prefer leaving my histogram in Photoshop CS6 in RGB mode, yet everytime I close the program and re-open photoshop, it defaults to Colors when I open a new document. Does anyone know how to get it to retain the RGB readout as a default? John