Reputation: 138
I have a JFrame with a Canvas in it (sacrilege, I know). The Canvas has an attached MouseListener and KeyListener, and has requested focus with:
canvas.setFocusable(true);
canvas.requestFocusInWindow();
When I first run it everything behaves as expected with events flying all over the place. After a few seconds it stops responding to normal key input (keyPressed and keyTyped are not being triggered). Bizarrely, holding clover (I'm on OSX) makes everything work normally.
What's going on? Why does this happen and what can I do to fix it?
Edit: I've figured out what behavior triggers the bug. It only starts happening when you hold down a key. When you release it, keyPressed events stop triggering. Below is my MCVE.
import java.awt.Canvas;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.image.BufferStrategy;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class Listener implements MouseListener,KeyListener {
JFrame frame;
Canvas screen;
public Listener() {
// initialize the screen canvas
screen = new Canvas();
Dimension size = new Dimension(640, 480);
screen.setMinimumSize(size);
screen.setMaximumSize(size);
screen.setPreferredSize(size);
screen.addMouseListener(this);
screen.addKeyListener(this);
screen.setFocusable(true);
// initialize the frame
frame = new JFrame("Parasite");
frame.add(screen);
frame.pack();
frame.setVisible(true);
screen.requestFocusInWindow();
// create buffer strategy (after showing frame)
screen.createBufferStrategy(2);
}
public static void main(String[] args) {
Listener listener = new Listener();
}
public void mouseClicked(MouseEvent e) {
System.out.println("click");
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void keyTyped(KeyEvent e) {
System.out.println("t " + e.getKeyChar());
}
public void keyPressed(KeyEvent e) {
System.out.println("p " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
System.out.println("r " + e.getKeyChar());
}
}
Upvotes: 1
Views: 823
Reputation: 138
Turns out the bug was induced by some devious interaction with the accents menu on osx. The system default (at least for Yosemite) is for it to pop up a menu offering you accented vowels when you hold down a letter key. Although it wasn't displaying the menu, it must have been doing something behind the scenes that messed with the focus.
Turning off the accents menu fixed the problem. For those unwilling to click through, type the following into your terminal.
defaults write -g ApplePressAndHoldEnabled -bool false
Upvotes: 1