Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 4186905
Votes 132
Synopsis JTextPane no longer dispatches keyTyped events to a KeyListener
Category java:classes_swing
Reported Against 1.2 , 1.1.6 , 1.2.1 , 1.2fcs , 1.2rc1 , 1.2rc2 , 1.2beta4
Release Fixed 1.2.2, 1.3(kestrel) (Bug ID:2023665)
State 10-Fix Delivered, bug
Priority: 2-High
Related Bugs 4159610 , 4191032 , 4197167 , 4200735 , 4245061 , 4298552
Submit Date 03-NOV-1998
Description
********************************************************************************

This bug record is specific to Java 2 SDK Standard Edition v. 1.2 and v. 1.2.1.

Please do not add customer calls relating to 1.1.x to this record.

********************************************************************************




/*
JTextPane no longer dispatches keyTyped events

The following code reproduces this problem.
When run under i586/win_nt_4.0 you will see
only the keyPressed and keyReleased events.

Run the same demo under SPARC/Solaris and you
will see keyPressed, keyTyped and keyReleased
for each key you strike.

This showed up under JDK 1.2 RC 1 and worked
fine under JDK 1.2beta4:
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * Demonstrates problems with JDK1.2 RC 1--JTextPane no longer
 * dispatches keyTyped events like it used to in JDK1.2beta4.  Typing
 * some characters in the pane after startup will show that only
 * keyPressed and keyReleased events are generated...
 */
public class TestJTP  {
    private static final float INITIAL_DOC_HEIGHT_PERCENT = 0.20f;
    private static final float INITIAL_WIDTH_PERCENT = 0.37f;
    public static void main(String[] argv) {
        JFrame aFrame = new JFrame();
        Dimension aScreenRes = Toolkit.getDefaultToolkit().getScreenSize();
        aScreenRes.height = (int) (INITIAL_DOC_HEIGHT_PERCENT
                                   * aScreenRes.height);
        aScreenRes.width = (int) (INITIAL_WIDTH_PERCENT
                                  * aScreenRes.width);
        JTextPane itsTextPane = new JTextPane();
        JScrollPane itsScrollPane = new JScrollPane(itsTextPane,
                                   JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        itsScrollPane.setPreferredSize(aScreenRes);
        // Register the listener to keep track of keyboard events:
        itsTextPane.addKeyListener(
                                   new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                System.out.println("Key type detected:" + e.getKeyChar());
            }
            public void keyPressed(KeyEvent e) {
                System.out.println("Key press detected:" + e.getKeyChar());
            }
            public void keyReleased(KeyEvent e) {
                System.out.println("Key release detected:" + e.getKeyChar());
            }
        }
        );
        aFrame.getContentPane().setLayout(new BorderLayout());
        aFrame.getContentPane().add(itsScrollPane, "Center");
        aFrame.pack();
        aFrame.setVisible(true);
    }
}

(Review ID: 41481)
======================================================================


  xxxxx@xxxxx   1999-01-19

JTextfield has the same problem 
Work Around
Add an InputMethodListener to the component. The sequence of characters entered is the combination of characters in KEY_TYPED key events and committed characters in input method events.
  xxxxx@xxxxx   1999-04-28
Evaluation
On windows, instead of a KeyTyped event being dispatched an InputMethodEvent of type INPUT_METHOD_TEXT_CHANGED is being passed in.
JTextComponent, in the constructor, does a enableEvents(AWTEvent.INPUT_METHOD_EVENT_MASK) which is why the input methods are enabled. The JTextCompoments will add the text via the processInputMethodEvent method, which is why new text is displayed even though the keyTyped isn't passed on. I am reassigning this to classes_awt_im and bumping the priority.
scott.violet 1999-03-22


  xxxxx@xxxxx   implemented a compatibility mode in JTextComponent for applications that do not handle input method events. In this compatibility mode, key events are generated from committed text and sent to the component via processKeyEvent. The implementation has been put back, but I'm still planning to add documentation to describe JTextComponent's interaction with input methods. This documentation has to be different for Swing in Java 2 and Swing for 1.1.
  xxxxx@xxxxx   1999-04-07

The documentation was updated for the Cricket Q build.
  xxxxx@xxxxx   1999-04-28
Comments
  
  Include a link with my name & email   

Submitted On 28-NOV-1998
duale
this is also a bug for JTextField and RC2, 
by the way, and prolly for any JTextComponent 
subclass.  i also cannot believe this bug exists!
how are you guys testing java, anyway???
also the suggested workaround is NOT valid
in that when
keytyped events _do_ finally work, your code will
break.  worksarounds should work under the
condition that 1) the bug exists and 2) the bug
has been fixed.



Submitted On 05-DEC-1998
sch1
I second duale above in that I can't believe that
this bug exists.  It is even in JDK1.2 fcs !  This
is really bad because one can't do much from 
keyPressed(), for instance setKeyChar() is not 
effective from keyPressed().


Submitted On 07-DEC-1998
NickC
I too am more than suprised that this bug made it passed 1.2 testing!
Nick


Submitted On 08-DEC-1998
olywa
may or may not be related - Insert does not toggle
insert/overstrike


Submitted On 10-DEC-1998
olywa
Bug is in all JTextComponents in 1.2 final.  Also 
consumed key events (consuming pressed, released, 
and typed) are still making it to 
JTextField so its listener must be getting keys 
before registered listeners.


Submitted On 10-DEC-1998
olywa
code snippet demonstrating consumed events still 
making it textfield
public class testconsume extends Frame {
   public static void main(String args[]) { new testconsume(); }
   public testconsume() {
      JTextField tf = new JTextField("             ");
      add(tf);
      tf.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) { e.consume(); }
            public void keyReleased(KeyEvent e) { e.consume(); }
            public void keyTyped(KeyEvent e) { e.consume(); }
         });
      pack();
      setVisible(true);
   }
}


Submitted On 10-DEC-1998
jasonlcl
I hope this gets fixed asap because we've 
converted all prgs to JDK1.2 from 1.2beta4.
Like the others, I feel this shouldn't be 
happening especially because it works ok in
beta4.


Submitted On 10-DEC-1998
alanchao
This is really bad cause it used to work under 1.1.6.
We're effectively stopped from moving to JDK1.2 
Please get this fix ASAP. 


Submitted On 14-DEC-1998
alanchao
We were able to workaround this by using InputMethodListener.
I believe it's the InputMethodEvent that's solely responsible
for updating the text in the textComponent and it's dispatched
after the keyEvent.  You could still use the keyEvent to find out
what was typed in and turn of/off a boolean and use the boolean
in the processInputEvent to determine if the key should be rejected
by not calling/calling the base class's processINputEvent.
Even changing the typed character(like upperCasing) is possible
by asking the base class's processInputEvent to process a recreated
InputMethodEvent which has the character turned upperCase.
Code sniplet:
 protected void processInputMethodEvent( InputMethodEvent kEvent )
  {
    CharacterIterator ci = kEvent.getText();
    int i = kEvent.getCommittedCharacterCount();
//  if key valid 
    {
//     if needs to turn to uppercase
       {
          ci.setIndex( i-1 );
          char c = ci.current();
          if ( Character.isLowerCase( c ) )
          {
             char[] caCharacter = new char[1];
             caCharacter[0] = c;
             String strCharacter = new String( caCharacter );
             strCharacter = strCharacter.toUpperCase();
             AttributedString s = new AttributedString( strCharacter );
             InputMethodEvent nEvent =
               new InputMethodEvent( (Component) kEvent.getSource(),
                                     kEvent.getID(),
                                     s.getIterator(),
                                     kEvent.getCommittedCharacterCount(),
                                     kEvent.getCaret(),
                                     kEvent.getVisiblePosition() );
             super.processInputMethodEvent( nEvent );
             return;
          }
       }
       super.processInputMethodEvent( kEvent );
    }
  }


Submitted On 07-JAN-1999
dlemire
It should be a priority for your bug killer team.


Submitted On 09-FEB-1999
alan griffiths
Are 4200559 and 4191032 also manifestations of 
the same bug? (The evaluation of 4200559 appears
to suggest that the JVM/AWT code isn't generating
the correct events.)


Submitted On 10-FEB-1999
gmarch
Oh boy, yet another showstopper that got released.
I wish I had such a crack QA team working for me.


Submitted On 11-FEB-1999
madarapu
This is also for the JTextField, this is irritating. This needs to be figured
out immediately. It is causing delay in my project. And why don't you provide
some code in the workaround.


Submitted On 07-APR-1999
DarwinWhaley
What's sad is that this bug was identified in November.  This is not just a
little nuisance - it is a major bug that will prevent many projects, including
mine, from moving to JDK 1.2.
Sun - PLEASE post an ETA for the fix!!!


Submitted On 08-APR-1999
keithw
This seems to work in Swing-1.1.1-beta1


Submitted On 15-APR-1999
Fahruz
I won't be original in saying that this bug is
pathetic and terribly annoying. Get it fixed right
away ! It also severely hinders my project from
continuing.


Submitted On 16-APR-1999
philp
I believe alanchao has a viable work around.
I was able to consume non numeric characters in
my JNumericField. Of course now I have to figure
out how to stop the pasting of non-numeric text 
into my JNumericField. :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
public class JNumericField extends JTextField
{
    public JNumericField()
    {
        super(null, null, 0);
    }
    /*
    public void processKeyEvent(KeyEvent e)
    {
        // this is what one would expect to work but it doesn't because
        // KEY_TYPED events never get here and they are the only ones
        // that when consumed will successfully stop a non numeric
        // character from being displayed in the text field.
        if (Character.isDigit(e.getKeyChar())
        ||  isSpecial(e.getKeyChar())
            super.processKeyEvent(e) ;
        else
            e.consume();
    }
    */
    protected boolean isSpecial(char c)
    {
        if ((c == KeyEvent.VK_TAB)
        ||  (c == KeyEvent.VK_ENTER)
        ||  (c == KeyEvent.VK_BACK_SPACE)
        ||  (c == 127)
        ||  (c == 27)
        ||  (c == KeyEvent.VK_LEFT)
        ||  (c == KeyEvent.VK_HOME)
        ||  (c == KeyEvent.VK_END)
        ||  (c == KeyEvent.VK_RIGHT))
            return true;
        else
            return false;
    }
    protected void processInputMethodEvent(InputMethodEvent event)
    {
        CharacterIterator ci = event.getText();
        int i = event.getCommittedCharacterCount();
        ci.setIndex(i-1);
        char c = ci.current();
        if (Character.isDigit(c)
        ||  isSpecial(c))
            super.processInputMethodEvent(event);
        else
            event.consume();
    }
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(new JNumericField(),
            BorderLayout.NORTH);
        frame.setSize(200, 200);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
    }
}


Submitted On 26-APR-1999
MWenk
This bug is also preventing the method 
setDefaultAction from working properly.
How about a little hint if and when this will be
fixed?  


Submitted On 28-APR-1999
glista
Arrrrggghhh! This bug has been a major pain.
What release of JFC is the fix slated for?  And
when will JFC 1.1.1 be incorporated into JDK 1.2 when
its finilized?


Submitted On 28-APR-1999
MWenk
How can I get the fix?


Submitted On 28-APR-1999
duale
FIXED GUYS!  Let's all give 'em a hand,
whaddya say, eh???



Submitted On 29-APR-1999
rmm20
I am really happy that this show-stopper problem,
reported in November, is now marked fixed and
closed so I can no longer vote for it.
So how do I obtain the fix for this "Fixed and
Closed" problem for Java 2????
 - Thanks - Robert Mitchell


Submitted On 12-MAY-1999
jmrozak
***This workaround is also posted in 
bug 4200559***
When working with JDK 1.2.0 under Win95/NT I've
noticed this in JTextField as well, that Alt+x
inserts an 'x' into the field in addition to
processing the Alt+x combo.
I have a workaround for this, and have added it
to my 'SwingText' package of Open Java Source
components, found at:
http://www.enteract.com/~goose/java/swingtext
The workaround goes like this:
1)  Establish an object-wide flag like "altIsDown".
2)  in keyPressed(), if the Alt key is pressed,
    set (altIsDown = true).
3)  in processInputMethodEvent(), only if the 
    Alt key is NOT pressed, forward the event
    to its parent.  Then clear the flag:
    if(! altIsDown) super.processInputMethodEvent();
    altIsDown = false;
In my environment, at least, mnemonic key handling
still works OK when using this workaround.  
Care must be taken to re-enable the field
during Alt-Tab, dialog popups, etc.  Note
that putting the (altIsDown = false) in the
processInputMethodEvent() handler is easier than
trying to reset it in keyReleased(), focusGained(),
etc.  


Submitted On 18-JUN-1999
fadil_mesic
First rule in programming with JDK should be: "Before you start to pull
your hair why something obviously correct doesn't work look at the Sun's java
site". After spending two weeks to figure out what is wrong with my code I
finally realised that everything is OK, except JDK.
BTW where is that fix or should I download a new version of "buggy"
JDK?


Submitted On 14-JUL-1999
javamatt
THIS BUG IS NOOOOOOOT FIXED!!!!!!!



Submitted On 08-OCT-1999
gjcullen
This problem also exists in JTextArea and JScrollPane.  What version and point
level will this KeyTyped problem be fixed? 


Submitted On 13-OCT-1999
doerga
This bug is killing me, and my boss (and his stupid deadline) is breathing down
my neck....
where can I get the fix (i'm already using the latest jdk...)


Submitted On 22-NOV-1999
MiguelM
If you need to filter keystrokes for numeric fields, one way to work around
this might be to do it in the Document class. Try creating a new class that
extends PlainDocument, and override the insertString() method. You can do your
filtering there. This has the added advantage of working for pasted text, as
well.
  private class NumberDocument extends PlainDocument
  {
    public void insertString(int offset, String str, AttributeSet atr)
      throws BadLocationException
    {
      StringBuffer newStr = new StringBuffer();
      String allowed = "1234567890";
      for (int ii=0; ii<str.length(); ++ii)
      {
        char thisChar = str.charAt(ii);
        if (allowed.indexOf(thisChar) >= 0)
          newStr.append(thisChar);
      }
      super.insertString(offset, newStr.toString(), atr);
    }
  }


Submitted On 24-NOV-1999
MiguelM
Although this bug is fixed, I have discovered a bizarre case where the bug will
show up again. If you override the processInputMethodEvent() method, you will
reintroduce this bug, even if your overridden method doesn't do anything
special. For example, if you override it like this:
  protected void processInputMethodEvent(InputMethodEvent e)
  {
    super.processInputMethodEvent(e);
  }
This bug will reappear. (Weird, huh?) 
I discovered this by incorporating MattJ1's workaround to bug 4127078, titled
"Mnemonic & Accelerator chars also written to JTextField."


Submitted On 07-DEC-1999
MiguelM
The bug report ID for the above bug is 4297027. [That's the bug with overriding
processInputMethodEvent()]


Submitted On 10-MAY-2000
phbuckle
This report is marked "Closed, Fixed"

It may be closed, but it's not fixed.

I need to process a user entry after the user presses the enter key.  
So it's either InputMethodEvent or KeyEvent.  But they break JTextField/Area as 
described in all the previous comments.  I fail to see how Document can help with this.

PaulB


Submitted On 17-AUG-2000
rizqureshiQ
Well, I cannot make my KeyListener to work on JTextField 
and I am using Java 1.3 with JFC 1.1.
The bug is far from fixed and very far from being closed!!


Submitted On 25-AUG-2000
sandor@wsi.net
I do not experience this error when running Java under Linux
(v1.2) but it shows up in the Windows version (v1.2 & v1.3).

I read elsewhere that Sun plans to merge the Blackdown and
Sun code bases. Perhaps someone at Sun can look at how the
Blackdown guys made it work in their implementation.

I previously devised a scheme that allowed me to "fake" the
KeyTyped event (I "manually" sent it to my listeners). 
Unfortunately, the work around does not work with the latest
JRE release (which is what we use!).

We have a mission critical application that is not working
because of this.


Submitted On 27-OCT-2000
rogerpromed
I would also like this bug fixed.
thanks,
Roger.


Submitted On 29-NOV-2000
ravitadaka
sir 

we are not getting how to control the keys which defind 
in MS windows 95,98,nt
i mean when i press Alt+tab it is displaying a dialog box 
which are opend 
instad of that i want to display display in a dialog box 
that "we are using swings"
how?
how i control all the keys ?

alt+f4 means it close the window 

but my require is i dont want to give the permition directly
close the window instade of close button 
if you have any idea on this topic  please
send mail to tadaka_ravi@yahoo.com    or
tadaka_ravi_chandra@usa.net

thankyou sir
by ravichandra




PLEASE NOTE: JDK6 is formerly known as Project Mustang