Search code examples
javaawtkeylistenerjappletkeystroke

Getting confused while using KeyListener's 3 methods in Swing?


I'm trying to build a textfield which can accept only numbers. I tried many times but I'm getting the behavior of 3 methods. The three methods call at same time, but all methods return different values for getKeyCode() method. Why do these methods return different values? And another thing, when I tried for adding keyListener to JApplet, it doesn't accept key values? Why?

import java.awt.event.*;
import javax.swing.*;

public class SimpleKey1 extends JApplet implements KeyListener
{
     String msg="";


     JTextField jTextField;
     int x = 10, y = 20; 

     public void init()
     {
         addKeyListener(this);

         requestFocus();
     }

     @Override
     public void keyPressed(KeyEvent arg0) {
        showStatus("Key Pressed");
     }

     @Override
     public void keyReleased(KeyEvent arg0) {
        showStatus("Key Released");
     }

     @Override
     public void keyTyped(KeyEvent arg0) {
         msg+=arg0.getKeyChar();
         repaint();
     }

     public void paint(Graphics g)
     {
         g.drawString(msg, x, y);
     }

}

Solution

  • Use JFormattedTextField instead and provide format which accepts only numbers. No need to code so much for this reason.

    Documentation at http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html