Validate the TextField component according to the Key Event

Hi
I want to validate the TextField component in my program , such that when the user enters characters i want to restrict the character to be printed on the TextField.
help me
rgds
nissam

Hi
here is my code ..the thing is that i dont want to print the pressed character in the TextField...i am unable to catch the key press event with the code u given...
thanks
nisam
import java.awt.*;
import java.awt.event.*;
class TestKey
Frame frm;
     TextField test;
     Label result;
     TestKey()
     test = new TextField();
               TextArea ee =new TextArea();
          result = new Label();
          test.addKeyListener(new KeyAdapter()
//               e.getKeyChar() gets the key char typed.
          //public void processKeyEvent(KeyEvent e){
               /*if((e.getID()==KeyEvent.ITEM_EVENT_MASK))
               {//&&(e.getKeyChar()=='c')){
                    System.out.println("Charatcter...."+e.getKeyChar());
          public void keyPressed(KeyEvent e)
               int code = e.getKeyCode();
if(((code <= 57) && (code >= 48))|| code == 155 || code== 35 || code == 40||
                    code == 34 || code == 37 || code == 12 || code == 39 ||
                    code == 36 || code == 38 || code == 33 || code == 106)
                    e.setKeyCode('\0');
                    result.setText(""+e.getKeyCode());
                    else
                         return;
     public void set()
          frm=new Frame();
          test.setBounds(50,50,100,60);
          result.setBounds(50,140,250,50);
          frm.setSize(230,340);
          frm.setVisible(true);
          frm.add(test);
          frm.add(result);
     public static void main(String args[])
          TestKey testk =new TestKey();
          testk.set();

Similar Messages

  • Key events on the glasspane

    I'm trying to develop a glasspane that captures the key events as well as the mouse events.. In this example, the mouse events happen exactly the way I want them to, but I cannot for the life of me get a key event to register.. I've tried capturing keyTyped(), keyPressed(), and keyReleased() to no avail.. Dukes to whoever shows me the light,
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BCInv
        extends JFrame {
      JScrollPane jScrollPane1 = new JScrollPane();
      JTextArea jTextArea1 = new JTextArea();
      JScrollPane jScrollPane2 = new JScrollPane();
      JTable jTable1 = new JTable();
      JButton jButton1 = new JButton();
      public BCInv() {
        jbInit();
        setVisible(true);
        getGlassPane().setVisible(true);
        //here I'm adding both listeners in the same manner
        getGlassPane().addMouseListener(new BCInv_mouseAdapter());
        getGlassPane().addKeyListener(new BCInv_keyAdapter());
      public void jbInit() {
        setSize(new Dimension(611, 423));
        getContentPane().setLayout(null);
        jScrollPane1.setBounds(new Rectangle(9, 275, 574, 110));
        jTextArea1.setText("jTextArea1");
        jScrollPane2.setBounds(new Rectangle(10, 13, 573, 175));
        jButton1.setBounds(new Rectangle(196, 217, 89, 42));
        jButton1.setText("jButton1");
        this.getContentPane().add(jScrollPane1, null);
        this.getContentPane().add(jScrollPane2, null);
        this.getContentPane().add(jButton1, null);
        jScrollPane2.getViewport().add(jTable1, null);
        jScrollPane1.getViewport().add(jTextArea1, null);
      public static void main(String[] args) {
        BCInv BC = new BCInv();
      //this key stuff here never executes..
      void BCkey(KeyEvent e) {
        System.out.println("A key was typed: '"+e.getKeyChar()+"' = "+e.getKeyCode());
      class BCInv_keyAdapter extends java.awt.event.KeyAdapter {
        BCInv_keyAdapter() {}
        public void keyTyped(KeyEvent e) {
          BCkey(e);
      //All this mouse stuff works great..
      void BCmouseClicked(MouseEvent e) {
        System.out.println("click");
        Point glassPanePoint = e.getPoint();
        boolean inButton = false;
        boolean inMenuBar = false;
        Component component = null;
        Container container = getContentPane();
        Point containerPoint = SwingUtilities.convertPoint(
            getGlassPane(),
            glassPanePoint,
            getContentPane());
        component = SwingUtilities.getDeepestComponentAt(
            container,
            containerPoint.x,
            containerPoint.y);
        if (component == null) {
          return;
        System.out.println("underlying component="+component.toString());
      class BCInv_mouseAdapter
          extends java.awt.event.MouseAdapter {
        BCInv_mouseAdapter() {}
        public void mouseClicked(MouseEvent e) {
          BCmouseClicked(e);
    }

    * @author nordj
    public class GlassPane extends JPanel {
         private boolean okToLooseFocus = true;
         public GlassPane() {
              setName("GlassPane");
              setVisible(false);
              super.setOpaque(false);
              //super.setBackground(new Color(0x00,0x00,0x00,0x88));
              //super.setForeground(new Color(0x00,0x00,0x00,0xFF));
              // trap keyboard & mouse events.
              //enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK);
              enableEvents(0xFFFFFFFFFFFFFFFFl);
              setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              setInputVerifier(new GlassPaneInputVerifier());
         /* (non-Javadoc)
          * @see java.awt.Component#processMouseEvent(java.awt.event.MouseEvent)
         protected void processMouseEvent(MouseEvent e) {
              if (e.getID() == e.MOUSE_CLICKED) {
                   Toolkit.getDefaultToolkit().beep();
                   e.consume();
              super.processMouseEvent(e);
         /* (non-Javadoc)
          * @see java.awt.Component#processKeyEvent(java.awt.event.KeyEvent)
         protected void processKeyEvent(KeyEvent e) {
              Toolkit.getDefaultToolkit().beep();
              super.processKeyEvent(e);
         /* (non-Javadoc)
          * @see java.awt.Component#processEvent(java.awt.AWTEvent)
         protected void processEvent(AWTEvent e) {
              // TODO Auto-generated method stub
              //System.err.println(e);
              super.processEvent(e);
         /* (non-Javadoc)
          * @see java.awt.Component#setVisible(boolean)
         public void setVisible(boolean visible) {
              okToLooseFocus = !visible;
              super.setVisible(visible);
              if (visible) {
                   requestFocusInWindow();
         /* (non-Javadoc)
          * @see java.awt.Component#paint(java.awt.Graphics)
         public void paint(Graphics g) {
              g.setColor(new Color(0xFF,0x00,0x00,0x88));
              g.fillRect(0,0,getWidth(), getHeight());
          * Simple hack to stop the RootPane loosing focus when it's visible
          * @author nordj
         private class GlassPaneInputVerifier extends InputVerifier {
              /* (non-Javadoc)
               * @see javax.swing.InputVerifier#verify(javax.swing.JComponent)
              public boolean verify(JComponent input) {
                   //return (!isVisible());
                   return okToLooseFocus;
    }

  • How to distinguish is cell get key event or mouse event in table?

    Hi!
    I have a JTable.
    1.Select cell and double click. As result caret is show
    2.Select cell and start type. As result caret is show
    How distinguish is caret is show, because cell get mouse event or key event?
    Thank you.

    Hm ...
    the problem with the key events is, that they are partically taking place in an editor component - but the double click of the mouse clicked on a cell, which is not currently edited, can be get by a MouseListener added to the JTable.
    My idea to that is as follows - hold the double_clicked state in a boolean variable hold by your JTable subclass - it is set by a MouseListener added to the JTable - and reset by the overwritten prepareEditor(...) method. This method should do the following:
    // say, double_clicked is a boolean field in your JTable subclass
    public Component prepareEditor(TableCellEditor editor,int row,int column) {
    Component c = super.prepareEditor(editor,row,column);
    if ((!double_clicked)&&(c instanceof JTextField)) { ((JTextField) c).setText(""); }
    double_clicked = false;
    return c;
    }now you have only to implement an add a MouseListener to your JTable subclass which detects this double click and sets the double_clicked field accordingly.
    This is an idea on the fly - hope it is helpful for you.
    greetings Marsian

  • Which components catch a key-event?

    Hello,
    I've a question. I've a panel with severall sub-panels with textfield-editors. These have listeners to respond on a enter-key pressed event.
    When I input an illegal value somewhere, I invoke a messagedialog with a warning message. The problem is that when I press enter , the oke-button of the messagepane has the focus, the enter-key pressed event is also caught by my first panel with all the editors and shows the same message dialog again. Kinda like a loop.
    I thought that key-pressed event only where caught by the component/frame which has the focus, or am I wrong.
    Can anyone help me out here?
    Much Thanks
    Hugo Hendriks

    Normally an ActionListener is installed to an OK button, not a KeyListener. Check if you have implemented the same error handling in two places!
    Generally you can "eat" key events by e.consume(), maybe this helps:
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
    // ... do some error handling on ENTER
    e.consume();
    I think then the Frame GUI will no get the key event anymore. A modal JDialog has a local event queue (to be modal), but maybe it forwards events to the main queue ...

  • 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

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

  • Order of key events

    Hello,
    I have a relaitevly simple question. In what order key events are received in the containment hierachy? For instance, if I have a frame, containing a panel which contains a text field and I implement KeyListener interface for each of these components, which component would receive a key event first?
    Thanks

    I have had the same problem... not to mention I made it worse trying to reset my manual settings for iphoto!!!!
    Now all of my stuff on my comupter is out of order!! : ( It will take me months to fix this. I often use iphoto on my ipad for work and it looks like that is not going to happen now!
    I am very unhappy about this apple people!
    DPM

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

  • TextInput key event delay

    We have a flash game (Tirnua) that uses a lot of display code (papervision3D for example) and a TextInput for a user chat input. We are seeing some performance problems (under IE mostly) where the TextInput key event is delayed by severals seconds from when the key was typed. This makes the chat very difficult to use. We do not lose the events.
    It seems the key event is delivered to the component by a callLater and that when the CPU is really busy, Later is too much later. Is that what's happening? Is there a way to control this delay?
    Thank you,
    Luc

    More information on this:
    After building a small prototype to analyse the problem, it seems that flash will deal with only one character per frame.
    So when the frame rate is low, the display of the text gets behind. Is there a way to get flash to deal with all the keys in the event queue every frame?
    Thank you,
    Luc

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

  • Tricky Block Key Events in JTable

    Iam using a JTable . I donot want to use CustomTableModel to block the key events but I want to consume the keyevents as and when the user types in . In other words block the user from editing the cell but I donot want to make the cell un-editable . THis is a bit tricky I hope I have a solution for this

    Not sure exactly what you want but maybe this will give you some ideas:
    table = new JTable(model)
         protected void processKeyEvent(KeyEvent e)
              int column = table.getSelectedColumn();
              int row = table.getSelectedRow();
              if( row == ?? && column == ?? )
                   e.consume();
               else
                   super.processKeyEvent(e);
    };

  • Adobe reader control kills key events

    I am using visual studio express 2013 on Win7 professional (x64) to write a private c# form application.
    Adobe reader is installed and added to my project.
    The control shows a pdf, wounderful.
    But at the moment, my form has the adobe reader control, no key events where triggered.
    Without the control: all works fine.
    I record a video to show my problem: https://www.youtube.com/watch?v=V0Vo2p2jz9M
    Is there a solution or workaround to give the key events to my form?
    Are more information needed?
    Thanks a lot.

    Check if you have full access to
    HKEY_CLASSES_ROOT\AcroExch.FDFDoc and sub keys,
    Disable any antivirus or backup applications while installing Reader.

  • Key Events

    Hi everyone,
    I have a question about key events. In the key events they have some values called as follows:
    static int KEY_LOCATION_LEFT
    static int KEY_LOCATION_NUMPAD
    static int KEY_LOCATION_RIGHT
    static int KEY_LOCATION_STANDARD
    I have seen the api and the explanation of what the above values represent
    and still do not understand what they mean.
    Is is possible for someone to explain these values to me in detail.
    What do they mean by LOCATION_LEFT - Left of what?
    What do they mean by LOCATION_RIGHT - right of what?
    What do they mean by LOCATION_STANDARD - what standard are they talking about?
    What do they mean by LOCATION_NUMPAD - are they talking about the num pad on the right of my keyboard?
    Any help is greatly appreciated
    Thank You
    Yours Sincerely
    Richard West

    First this (http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html) tutorial is pretty helpful with this, try playing with the program there
    What do they mean by LOCATION_LEFT - Left of what?
    so far keys that produce the LEFT location things like 'left shift', 'left ctrl'....
    What do they mean by LOCATION_RIGHT - right of what?
    like left, but ie 'right shift' is a right location key
    What do they mean by LOCATION_STANDARD - what
    standard are they talking about?
    all keys that only have one instance and are NOT on the numberpad
    What do they mean by LOCATION_NUMPAD - are they
    talking about the num pad on the right of my
    keyboard?yes, NUMPAD refers to numbers and other keys on the right side of the keyboard

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

  • Getting Key Events during animation loop

    I'm having a problem recieving Key events during my animation loop. Here is my example program
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import javax.swing.JPanel;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import java.util.ArrayList;
    import java.awt.event.*;
    import java.util.Iterator;
    import GAME.graphics.Animation;
    import GAME.sprites.MainPlayer;
    import GAME.util.MapData;
    import GAME.input.*;
    public class ImageTest extends JFrame {
        private static final long DEMO_TIME = 20000;
        private Animation      anim;
        private MainPlayer     mPlayer;
        private MapData               mapData;
        private InputManager      inputManager;
        private GameAction moveLeft;
        private GameAction moveRight;
        private GameAction exit;
        public ImageTest()
         requestFocus();
         initInput();
         setSize(1024, 768);
         setUndecorated(true);
         setIgnoreRepaint(true);
         setResizable(false);
         loadImages();
         anim = new Animation();
            mPlayer = new MainPlayer(anim);
            setVisible(true);
            createBufferStrategy(2);
            animationLoop();
         // load the player images
         private void loadImages()
              // code that loads images...
         // Initialize input controls
         private void initInput() {
            moveLeft = new GameAction("moveLeft");
            moveRight = new GameAction("moveRight");
            exit = new GameAction("exit",
                GameAction.DETECT_INITAL_PRESS_ONLY);
            inputManager = new InputManager(this);
            inputManager.setCursor(InputManager.INVISIBLE_CURSOR);
            inputManager.mapToKey(moveLeft, KeyEvent.VK_LEFT);
            inputManager.mapToKey(moveRight, KeyEvent.VK_RIGHT);
            inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
        // Check player input
        private void checkInput(long elapsedTime) {
            if (exit.isPressed()) {
                System.exit(0);
            if (mPlayer.isAlive()) {
                float velocityX = 0;
                if (moveLeft.isPressed()) {
                    velocityX-=mPlayer.getMaxSpeed();
                if (moveRight.isPressed()) {
                    velocityX+=mPlayer.getMaxSpeed();
                mPlayer.setVelocityX(velocityX);
        // main animation loop
        public void animationLoop() {
            long startTime = System.currentTimeMillis();
            long currTime = startTime;
            while (currTime - startTime < DEMO_TIME) {
                long elapsedTime =
                    System.currentTimeMillis() - currTime;
                currTime += elapsedTime;
                checkInput(elapsedTime);
                mPlayer.update(elapsedTime);
                // draw and update screen
                BufferStrategy strategy = this.getBufferStrategy();
                Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
                if (!(bgImage == null))
                     draw(g);
                     g.dispose();
                     if (!strategy.contentsLost()) {
                         strategy.show();
                // take a nap
                try {
                    Thread.sleep(20);
                catch (InterruptedException ex) { }
        public void draw(Graphics g) {
            // draw background
            if (bgImage != null)
                         // draw image
                 g.drawImage(mPlayer.getImage(), (int)mPlayer.getX(), (int)mPlayer.getY(), null);
    }My InputManager implements KeyListener. When running print statements on my Key events, they are not being called until after the animation demo is done running. Can someone help me with getting the Key events to update during the animation loop? Thank you!

    I've used the post from Abuse on the following thread with success. Maybe it will clue you in to what you might be doing wrong:
    http://forum.java.sun.com/thread.jsp?forum=406&thread=498527

Maybe you are looking for