Solved

How to Stop an KeyPressed Event in JTextField ?

Posted on 2001-09-18
9
3,328 Views
Last Modified: 2006-11-17
I have inherited a TextField from com.sun.java.swing.JTextField and implements java.util.EventListener.KeyListener interface. I am trying to avoid to display a character "A" or "a", when user typed that charater. First I tried in java.awt.TextField, it worked. Then, I tried with JTextField, It didn't work. My code is:

import java.awt.*;
import java.awt.event.*;
import com.sun.java.swing.*;

public class MTextField extends JTextField implements KeyListener
{

  public MTextField()
  {
      super();
      this.addKeyListener(this);
  }

  //Implementing KeyListener Events
  public void keyPressed(KeyEvent e)
  {
        int keycode     = e.getKeyCode();
        if (keycode == 65) //Stop the event, when "a" pressed
        {
            e.setKeyCode(e.VK_CANCEL);
        }
  }

  public void keyTyped(KeyEvent e)
  {
  }

  public void keyReleased(KeyEvent e)
  {
  }
}

In the JApplet, I am using this like:

MTextField MTF = new MTextField();
this.getContentPane().add(MTF, new XYConstraints(150, 25, 200, 25));

Any Help ?

0
Comment
Question by:UU1
9 Comments
 
LVL 1

Expert Comment

by:Lab_Rat
ID: 6490790
Isn't it something about inheriting the event handle?
0
 
LVL 9

Accepted Solution

by:
yongsing earned 50 total points
ID: 6490940
public class MTextField extends JTextField {
 
    public MTextField(int cols) {
        super(cols);
    }
 
    protected Document createDefaultModel() {
        return new MDocument();
    }
 
    static class MDocument extends PlainDocument {
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
 
            if (str == null) {
                return;
            }
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c != 'A' && c!= 'a') {
                    sb.append(c);
              }
            }
          super.insertString(offs, sb.toString(), a);
        }
     }
 }
0
 
LVL 1

Expert Comment

by:vbremaud
ID: 6491057
Stopping the event should work with:
  e.consume();
I remember having seen this in some codes...

hope it helps :-)
0
 
LVL 2

Expert Comment

by:vpadma
ID: 6491504
Try This:

import java.awt.*;
import java.awt.event.*;
import com.sun.java.swing.*;

public class MTextField extends JTextField implements KeyListener
{

 public MTextField()
 {
     super();
     this.addKeyListener(this);
 }

 //Implementing KeyListener Events
 public void keyPressed(KeyEvent e)
 {
       int keycode     = e.getKeyCode();
       if (keycode == 65) //Stop the event, when "a" pressed
       {
           e.consume(); //Consumes this event so that it will not be processed in the default manner by the source which originated it.

       }
 }

 public void keyTyped(KeyEvent e)
 {
 }

 public void keyReleased(KeyEvent e)
 {
 }
}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 92

Expert Comment

by:objects
ID: 6492108
There's no need to extend JTextField to implement what you require. Simply use a Document implementation as suggested by yongsing.

0
 
LVL 9

Expert Comment

by:yongsing
ID: 6492132
The Keylistener method will not work especially when you do a copy-and-paste onto the textfield.
0
 
LVL 92

Expert Comment

by:objects
ID: 6492138
Exactly, or if text is programatically added.
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 6492439
what yongsing said is exactly correct.
0
 
LVL 20

Expert Comment

by:Venabili
ID: 8916495
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- points for yongsing

Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Venabili
EE Cleanup Volunteer
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

943 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now