Solved

How to Stop an KeyPressed Event in JTextField ?

Posted on 2001-09-18
9
3,354 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
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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…
The viewer will learn how to implement Singleton Design Pattern in Java.

773 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