Problem with key events in applets
Davin McCall
davmac at davmac.org
Fri Jan 24 09:18:52 PST 2014
Hi,
I've noticed a problem with key events in applets - specifically, "key
released" are being inappropriately generated for some keys and not
generated at all for other keys. I have a small demo applet, live
version is here:
http://bluej.org/davmac/KeyApplet.html
The code is below. The applet presents a text area with an empty JPanel
beneath it. When you click the JPanel, it requests focus, and clears the
text area, and then key events (pressed, typed and released) are
reported in the text area. (Note that the entire applet initially
appears grey; just click near the bottom to restore the correct appearance).
For letter keys, pressing and holding a key causes a repeating sequence:
key pressed
key typed
key released
key pressed
key typed
key released
This is clearly incorrect; there should only be one 'key pressed' and
one 'key released' for each press/release of the key.
When an arrow key is pressed, held briefly and then released, the event
sequence is:
key pressed
key pressed
key pressed
... with no 'key released' events generated at all.
So, there seems to be a bug with key event handling. Is this a known bug?
Thanks,
Davin
Code:
=== KeyApplet.java ===
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyApplet extends JApplet
{
private JPanel nPanel;
public void init()
{
JRootPane rootPane = this.getRootPane();
final JTextArea textArea = new JTextArea("", 20, 60);
textArea.append("Running!\n");
rootPane.setLayout(new BorderLayout());
rootPane.add(textArea, BorderLayout.CENTER);
nPanel = new JPanel()
{
public Dimension getPreferredSize()
{
return new Dimension(500, 40);
}
};
nPanel.setFocusable(true);
nPanel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
textArea.getDocument().remove(0,
textArea.getDocument().getLength());
}
catch (Exception ble) {}
textArea.append("Clicked!\n");
nPanel.requestFocusInWindow();
}
});
rootPane.add(nPanel, BorderLayout.SOUTH);
nPanel.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
textArea.append("Key typed!\n");
}
public void keyReleased(KeyEvent e) {
textArea.append("Key released!\n");
}
public void keyPressed(KeyEvent e) {
textArea.append("Key pressed!\n");
}
});
}
public void start()
{
repaint();
nPanel.requestFocusInWindow();
}
}
More information about the macosx-port-dev
mailing list