Hi, I was wondering if there is any way to make the keylistener "listen" across the entire application? Currently whenever I've used it I have always attached it to something else, like a JTextField or the like. However that doesn't work all that well if I for example want to close down the current JDialog by pressing escape, because no object that has the keylistener attached to it is currently focused.
When I searched around for the answer if found similar questions on stackoverflow, but those seemed to focus on listening globally, even when the application itself is not focused, which isn't quite what I want.
Here is a simple piece of code that I'm currently experimenting with:
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; import java.security.spec.InvalidKeySpecException; import javax.swing.*; public class MainFrame implements KeyListener { JFrame frame; public static void main(String[] args) throws IOException, InvalidKeySpecException { new MainFrame(); } JPanel totalGUI; public JPanel createContentPane() { totalGUI = new JPanel(); JLabel someLabel = new JLabel("test"); someLabel.setSize(200,20); someLabel.setLocation(50,50); totalGUI.add(someLabel); return totalGUI; } public MainFrame() throws InvalidKeySpecException { frame = new JFrame(); frame.setContentPane(createContentPane()); frame.setSize(500,500); frame.setUndecorated(false); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); } @Override public void keyPressed(KeyEvent e) { if(e.getKeyChar() == KeyEvent.VK_D) { JOptionPane.showMessageDialog(null, "D pressed"); } if(e.getKeyChar() == KeyEvent.VK_A) { JOptionPane.showMessageDialog(null, "A pressed"); } } @Override public void keyReleased(KeyEvent e) { if(e.getKeyChar() == KeyEvent.VK_D) { JOptionPane.showMessageDialog(null, "D released"); } if(e.getKeyChar() == KeyEvent.VK_A) { JOptionPane.showMessageDialog(null, "D released"); } } @Override public void keyTyped(KeyEvent arg0) { } }
It's supposed to simply create a frame and give me a message whenever I press the A or D buttons, as well as notify me whenever they are released. As of currently it obviously doesn't work because the keylistener hasn't been attached to anything, but that's also where I'm unsure of how to proceed.
Any help is as always greatly appreciated!