Java JFrame not receiving input - java

I have a JFrame set up with a keyListener added onto it at runtime, but when the Frame loads, there is a brief moment in which input will be received and then it just stops receiving input all together, here is the Keyboard.java code:
package uk.connorwright.rain.input;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Keyboard implements KeyListener {
private boolean[] keys = new boolean[120];
public boolean up, down, left, right;
public void update() {
up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {
}
}
This is the code in Game.java which relates to the Keyboard input:
private Keyboard key;
...
key = new Keyboard();
frame.addKeyListener(key);
....
public void update() {
key.update();
if (key.up) {
y--;
}
if (key.down) {
y++;
}
if (key.left) {
x--;
}
if (key.right) {
x++;
}
}
...
public static void main(String[] args) {
Game game = new Game();

KeyListener is a poor choice, it's responsible for generating events for a component when it is focusable AND it has focus.
Instead, you should considering using the Key Bindings API, which provides you the means to decide at what focus level it should generate key events
See How to Use Key Bindings for more details.

I haven't tested this, but I think it's probable that your KeyListener needs a component which has the keyboard focus, and a JFrame will never have that. Only subcomponents of the frame will have the focus.
From the tutorial:
https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Specifically, key events are fired by the component with the keyboard
focus when the user presses or releases keyboard keys. For detailed
information about focus, see How to Use the Focus Subsystem.
So no key events if you don't have focus.

Related

Listening for the CAPS key [duplicate]

This question already has answers here:
KeyListener after Button Is Pressed
(2 answers)
Closed 6 years ago.
I have been trying to build a small utility that listens for when the user presses the "Caps Lock" key. The program should start and first display wheter the key is ON or OFF. The program should also listen for any changes, and update the frame accordingly.
Unfortunately, the only part I can get right is in the beginning, when the frame displays if the Caps key is on or off. After that, it gets stuck. Even if I press the key it changes nothing on screen.
The program is also supposed to produce a .beep() sound when the caps key is on, but it only works if I start it with the key on.
Code:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
JLabel label = new JLabel("CAPS LOCK IS ON!");
JLabel label1 = new JLabel("CAPS LOCK IS OFF!");
boolean check = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
if (check == true) {
frame.repaint();
frame.add(label);
Toolkit.getDefaultToolkit().beep();
} else {
frame.repaint();
frame.add(label1);
}
keyPressed(KeyCode.CAPS);
frame.show();
}
public static void keyPressed(KeyCode e) {
boolean check = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
if (check == true) {
Toolkit.getDefaultToolkit().beep();
}
}
EDIT: If you only want to know if the Caps key is toggled(on):
if (Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
label.setText("CAPS LOCK IS ON!");
Toolkit.getDefaultToolkit().beep();
} else {
label.setText("CAPS LOCK IS OFF");
}
This way it only beeps when the caps key is toggled and doesnt beep when is not toggled.
If you want to track "Caps Lock" only within your application, you can do something like:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher()
{
#Override
public boolean dispatchKeyEvent(KeyEvent e)
{
if (KeyEvent.VK_CAPS_LOCK == e.getKeyCode())
{
boolean check = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
// do something here
}
return false;
}
});
You also might need to track focus and update state when your app is re-focused.
However if you want your application to track Caps Lock system-wide as I suspect you do, than unfortunately you are out of luck. There is no way in pure Java to do it as this is a very OS-specific feature. Still for Windows there is a wrapper around C-code https://github.com/kristian/system-hook
As mentioned in other answers, your code isn't registering a KeyListener, so it's simply reading the locking state of the key once.
To capture the state change on CapsLock, You need to watch for the keyPressed (cap lock on) and keyReleased (cap lock off) separately.
Take a look at this example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class CapChecker {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
frame.add(label);
frame.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CAPS_LOCK && Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
label.setText("CAPS LOCK IS ON!");
Toolkit.getDefaultToolkit().beep();
} else {
label.setText("" + e.getKeyChar());
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_CAPS_LOCK) {
label.setText("CAPS LOCK IS OFF!");
}
}
});
frame.setVisible(true);
}
});
}
}
After the Frame is shown, your program does nothing. You have to register a KeyListener to the frame:
frame.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
})
In these methods you can react to key presses or releases.

How to use keyListener properly in Java

I am running into problems trying to use KeyListener in java.
I am trying to write a program that runs until a key is pressed, and then outputs that key.
This is a stepping stone to more elaborate code, so the use of a method to print the key pressed is just being used as a kind of prototype.
Here is the code:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class keylistener implements KeyListener{
public keylistener(){
addKeyListener(this);
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
keylistener output = new keylistener();
output.print(key);
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public void print(int key){
System.out.println(key);
}
public static void main(String[] args){
}
}
The program runs and then ends directly after.
I have never used KeyListener before, and I cannot figure out how to make the program wait for the key to be pressed.
The KeyListener is intended to be used in GUI apps, not in console apps as KeyListener requires GUI components to run. Usually in a console app you would use a BufferedReader and InputStreamReader.
Here is a console app that demonstrates the idea of using a while loop with the BufferedReader and InputStreamReader to keep the app running waiting for input. Although there are other ways to do this. I made this very explicit so you can grasp the concept.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StackStuff {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean runs = true ;
System.out.println("Press any key to kill this app...");
while(runs){
input =br.readLine();
if (!(input==null)){
System.out.println(input);
runs=false;
}
}
System.out.println("I am dead!!");
System.exit(0);
}
I don't think I've ever added a KeyListener to a console app, (probably because KeyListener is part of the AWT package, which mainly has GUI components), but here is a sample GUI app to demonstrate.
Your first problem, though, is that you should have added new keylistener() into your main method, though that has to be added to a component itself in order to be ran.
public class GuiMain extends JFrame { // A GUI Frame
public GuiMain() {
// Add the listener
this.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
// Print out the code
System.out.println(e.getKeyCode());
}
});
// Show something
add(new JLabel("Hello World!"));
pack();
}
public static void main(String[] args) {
// Run the GUI
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GuiMain gui = new GuiMain();
gui.setVisible(true);
}
});
}
}

KeyListener not reacting or being detected [JAVA] [duplicate]

I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:
System.out.println("test");
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) { System.out.println( "tester"); }
public void keyReleased(KeyEvent e) { System.out.println("2test2"); }
public void keyTyped(KeyEvent e) { System.out.println("3test3"); }
});
When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.
I was thinking that it could be because the focus is not on the JFrame
and so they KeyListener doesn't receive any events. But, I'm pretty sure it is.
Is there something that I am missing?
If you don't want to register a listener on every component,
you could add your own KeyEventDispatcher to the KeyboardFocusManager:
public class MyFrame extends JFrame {
private class MyDispatcher implements KeyEventDispatcher {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println("tester");
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
System.out.println("2test2");
} else if (e.getID() == KeyEvent.KEY_TYPED) {
System.out.println("3test3");
}
return false;
}
}
public MyFrame() {
add(new JTextField());
System.out.println("test");
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new MyDispatcher());
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.pack();
f.setVisible(true);
}
}
You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.
The process is the same:
myComponent.addKeyListener(new KeyListener ...);
Note: Some components aren't focusable like JLabel.
For setting them to focusable you need to:
myComponent.setFocusable(true);
InputMaps and ActionMaps were designed to capture the key events for the component, it and all of its sub-components, or the entire window. This is controlled through the parameter in JComponent.getInputMap(). See How to Use Key Bindings for documentation.
The beauty of this design is that one can pick and choose which key strokes are important to monitor and have different actions fired based on those key strokes.
This code will call dispose() on a JFrame when the escape key is hit anywhere in the window. JFrame doesn't derive from JComponent so you have to use another component in the JFrame to create the key binding. The content pane might be such a component.
InputMap inputMap;
ActionMap actionMap;
AbstractAction action;
JComponent component;
inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
actionMap = component.getActionMap();
action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
dispose();
}
};
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "dispose");
actionMap.put("dispose", action);
I got the same problem until i read that the real problem is about FOCUS the your JFrame has already added Listeners but tour frame is never on Focus because you got a lot of components inside your JFrame that also are focusable so try:
JFrame.setFocusable(true);
Good Luck
KeyListener is low level and applies only to a single component. Despite attempts to make it more usable JFrame creates a number of component components, the most obvious being the content pane. JComboBox UI is also often implemented in a similar manner.
It's worth noting the mouse events work in a strange way slightly different to key events.
For details on what you should do, see my answer on Application wide keyboard shortcut - Java Swing.
Deion (and anyone else asking a similar question), you could use Peter's code above but instead of printing to standard output, you test for the key code PRESSED, RELEASED, or TYPED.
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
dispose();
}
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
dispose();
}
} else if (e.getID() == KeyEvent.KEY_TYPED) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
dispose();
}
}
return false;
}
in order to capture key events of ALL text fields in a JFrame,
one can employ a key event post processor.
Here is a working example, after you add the obvious includes.
public class KeyListenerF1Demo extends JFrame implements KeyEventPostProcessor {
public static final long serialVersionUID = 1L;
public KeyListenerF1Demo() {
setTitle(getClass().getName());
// Define two labels and two text fields all in a row.
setLayout(new FlowLayout());
JLabel label1 = new JLabel("Text1");
label1.setName("Label1");
add(label1);
JTextField text1 = new JTextField(10);
text1.setName("Text1");
add(text1);
JLabel label2 = new JLabel("Text2");
label2.setName("Label2");
add(label2);
JTextField text2 = new JTextField(10);
text2.setName("Text2");
add(text2);
// Register a key event post processor.
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventPostProcessor(this);
}
public static void main(String[] args) {
JFrame f = new KeyListenerF1Demo();
f.setName("MyFrame");
f.pack();
f.setVisible(true);
}
#Override
public boolean postProcessKeyEvent(KeyEvent ke) {
// Check for function key F1 pressed.
if (ke.getID() == KeyEvent.KEY_PRESSED
&& ke.getKeyCode() == KeyEvent.VK_F1) {
// Get top level ancestor of focused element.
Component c = ke.getComponent();
while (null != c.getParent())
c = c.getParent();
// Output some help.
System.out.println("Help for " + c.getName() + "."
+ ke.getComponent().getName());
// Tell keyboard focus manager that event has been fully handled.
return true;
}
// Let keyboard focus manager handle the event further.
return false;
}
}
This should help
yourJFrame.setFocusable(true);
yourJFrame.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("you typed a key");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("you pressed a key");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("you released a key");
}
});
Hmm.. what class is your constructor for? Probably some class extending JFrame? The window focus should be at the window, of course but I don't think that's the problem.
I expanded your code, tried to run it and it worked - the key presses resulted as print output. (run with Ubuntu through Eclipse):
public class MyFrame extends JFrame {
public MyFrame() {
System.out.println("test");
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("tester");
}
public void keyReleased(KeyEvent e) {
System.out.println("2test2");
}
public void keyTyped(KeyEvent e) {
System.out.println("3test3");
}
});
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.pack();
f.setVisible(true);
}
}
I have been having the same problem. I followed Bruno's advice to you and found that adding a KeyListener just to the "first" button in the JFrame (ie, on the top left) did the trick. But I agree with you it is kind of an unsettling solution. So I fiddled around and discovered a neater way to fix it. Just add the line
myChildOfJFrame.requestFocusInWindow();
to your main method, after you've created your instance of your subclass of JFrame and set it visible.
lol .... all you have to do is make sure that
addKeyListener(this);
is placed correctly in your code.
You could have custom JComponents set their parent JFrame focusable.
Just add a constructor and pass in the JFrame. Then make a call to setFocusable() in paintComponent.
This way the JFrame will always receive KeyEvents regardless of whether other components are pressed.

Java - Want getKeyCode to only register once

I'm currently working on a little game. I'm using getKeyCode to move my character but the thing is that I don't want you to be able to keep moving if you hold in the button. Is there anyway I can use getKeyCode to only register on the first click and then won't register until I release the button and press again?
else if (event.getKeyCode()== KeyEvent.VK_UP)
{
spelare1.setLocation(spelare1.getX(),spelare1.getY()-50);
}
This is how it currently looks like.
I think you are confusing KeyEvents. VK_UP is the up arrow key. Use KeyEvent.KEY_RELEASED to react on a released key.
You can keep a boolean indicating whether the key is currently pressed. Then you can react once after each press, like in this example:
public static void main(String[] args) {
JFrame f = new JFrame();
f.addKeyListener(new KeyAdapter() {
private boolean pressed;
#Override
public void keyReleased(KeyEvent e) {
pressed = false;
}
#Override
public void keyPressed(KeyEvent e) {
if (!pressed) {
System.out.println("Key pressed: " + e.getKeyCode());
pressed = true;
}
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f.setVisible(true);
}
});
}
Depending on your needs, you might want to have a separate state for each key, or just one shared state.

Unresponsive KeyListener for JFrame

I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:
System.out.println("test");
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) { System.out.println( "tester"); }
public void keyReleased(KeyEvent e) { System.out.println("2test2"); }
public void keyTyped(KeyEvent e) { System.out.println("3test3"); }
});
When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.
I was thinking that it could be because the focus is not on the JFrame
and so they KeyListener doesn't receive any events. But, I'm pretty sure it is.
Is there something that I am missing?
If you don't want to register a listener on every component,
you could add your own KeyEventDispatcher to the KeyboardFocusManager:
public class MyFrame extends JFrame {
private class MyDispatcher implements KeyEventDispatcher {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println("tester");
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
System.out.println("2test2");
} else if (e.getID() == KeyEvent.KEY_TYPED) {
System.out.println("3test3");
}
return false;
}
}
public MyFrame() {
add(new JTextField());
System.out.println("test");
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new MyDispatcher());
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.pack();
f.setVisible(true);
}
}
You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.
The process is the same:
myComponent.addKeyListener(new KeyListener ...);
Note: Some components aren't focusable like JLabel.
For setting them to focusable you need to:
myComponent.setFocusable(true);
InputMaps and ActionMaps were designed to capture the key events for the component, it and all of its sub-components, or the entire window. This is controlled through the parameter in JComponent.getInputMap(). See How to Use Key Bindings for documentation.
The beauty of this design is that one can pick and choose which key strokes are important to monitor and have different actions fired based on those key strokes.
This code will call dispose() on a JFrame when the escape key is hit anywhere in the window. JFrame doesn't derive from JComponent so you have to use another component in the JFrame to create the key binding. The content pane might be such a component.
InputMap inputMap;
ActionMap actionMap;
AbstractAction action;
JComponent component;
inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
actionMap = component.getActionMap();
action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
dispose();
}
};
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "dispose");
actionMap.put("dispose", action);
I got the same problem until i read that the real problem is about FOCUS the your JFrame has already added Listeners but tour frame is never on Focus because you got a lot of components inside your JFrame that also are focusable so try:
JFrame.setFocusable(true);
Good Luck
KeyListener is low level and applies only to a single component. Despite attempts to make it more usable JFrame creates a number of component components, the most obvious being the content pane. JComboBox UI is also often implemented in a similar manner.
It's worth noting the mouse events work in a strange way slightly different to key events.
For details on what you should do, see my answer on Application wide keyboard shortcut - Java Swing.
Deion (and anyone else asking a similar question), you could use Peter's code above but instead of printing to standard output, you test for the key code PRESSED, RELEASED, or TYPED.
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
dispose();
}
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
dispose();
}
} else if (e.getID() == KeyEvent.KEY_TYPED) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
dispose();
}
}
return false;
}
in order to capture key events of ALL text fields in a JFrame,
one can employ a key event post processor.
Here is a working example, after you add the obvious includes.
public class KeyListenerF1Demo extends JFrame implements KeyEventPostProcessor {
public static final long serialVersionUID = 1L;
public KeyListenerF1Demo() {
setTitle(getClass().getName());
// Define two labels and two text fields all in a row.
setLayout(new FlowLayout());
JLabel label1 = new JLabel("Text1");
label1.setName("Label1");
add(label1);
JTextField text1 = new JTextField(10);
text1.setName("Text1");
add(text1);
JLabel label2 = new JLabel("Text2");
label2.setName("Label2");
add(label2);
JTextField text2 = new JTextField(10);
text2.setName("Text2");
add(text2);
// Register a key event post processor.
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventPostProcessor(this);
}
public static void main(String[] args) {
JFrame f = new KeyListenerF1Demo();
f.setName("MyFrame");
f.pack();
f.setVisible(true);
}
#Override
public boolean postProcessKeyEvent(KeyEvent ke) {
// Check for function key F1 pressed.
if (ke.getID() == KeyEvent.KEY_PRESSED
&& ke.getKeyCode() == KeyEvent.VK_F1) {
// Get top level ancestor of focused element.
Component c = ke.getComponent();
while (null != c.getParent())
c = c.getParent();
// Output some help.
System.out.println("Help for " + c.getName() + "."
+ ke.getComponent().getName());
// Tell keyboard focus manager that event has been fully handled.
return true;
}
// Let keyboard focus manager handle the event further.
return false;
}
}
This should help
yourJFrame.setFocusable(true);
yourJFrame.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("you typed a key");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("you pressed a key");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("you released a key");
}
});
Hmm.. what class is your constructor for? Probably some class extending JFrame? The window focus should be at the window, of course but I don't think that's the problem.
I expanded your code, tried to run it and it worked - the key presses resulted as print output. (run with Ubuntu through Eclipse):
public class MyFrame extends JFrame {
public MyFrame() {
System.out.println("test");
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("tester");
}
public void keyReleased(KeyEvent e) {
System.out.println("2test2");
}
public void keyTyped(KeyEvent e) {
System.out.println("3test3");
}
});
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.pack();
f.setVisible(true);
}
}
I have been having the same problem. I followed Bruno's advice to you and found that adding a KeyListener just to the "first" button in the JFrame (ie, on the top left) did the trick. But I agree with you it is kind of an unsettling solution. So I fiddled around and discovered a neater way to fix it. Just add the line
myChildOfJFrame.requestFocusInWindow();
to your main method, after you've created your instance of your subclass of JFrame and set it visible.
lol .... all you have to do is make sure that
addKeyListener(this);
is placed correctly in your code.
You could have custom JComponents set their parent JFrame focusable.
Just add a constructor and pass in the JFrame. Then make a call to setFocusable() in paintComponent.
This way the JFrame will always receive KeyEvents regardless of whether other components are pressed.

Categories