Solved

How to Stop an KeyPressed Event in JTextField ?

Posted on 2001-09-18
9
3,279 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
Comment Utility
Isn't it something about inheriting the event handle?
0
 
LVL 9

Accepted Solution

by:
yongsing earned 50 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 92

Expert Comment

by:objects
Comment Utility
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
Comment Utility
The Keylistener method will not work especially when you do a copy-and-paste onto the textfield.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Exactly, or if text is programatically added.
0
 
LVL 26

Expert Comment

by:ksivananth
Comment Utility
what yongsing said is exactly correct.
0
 
LVL 20

Expert Comment

by:Venabili
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
commonTwo  challenge 63 98
allStar challenge 1 40
topping3 challenge 14 48
Unable to start eclipse ? 17 82
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

771 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

12 Experts available now in Live!

Get 1:1 Help Now