Solved

How to Stop an KeyPressed Event in JTextField ?

Posted on 2001-09-18
9
3,459 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ejb wildfly example 2 113
Java 8 to Java 6 8 44
DTD and JAVA versions 1 59
How to log java errors in tomcat 8 39
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…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

752 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