Solved

How to Stop an KeyPressed Event in JTextField ?

Posted on 2001-09-18
9
3,513 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.
Suggested Courses

624 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