Again... I have another issue with the keyListener and the JFrame. I want to be able to add a keyListener to the JFrame while the JFrame is visible. My problem is that when I try this, the keyListener doesn't respond. Here is my code:
public JFrame frame = new JFrame("JFrame Test");
public static void main(String[]args) {
new JFrameTest();
}
public JFrameTest() {
frame.setSize(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.add(new space());
frame.validate();
frame.repaint();
}
@SuppressWarnings("serial")
public class space extends JPanel {
public space() {
setFocusable(true);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("Mouse Pressed!");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse Released!");
}
});
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed!");
}
public void keyReleased(KeyEvent e) {
System.out.println("Key Released!");
}
});
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(0, 0, frame.getWidth() / 2, frame.getHeight() / 2);
repaint();
}
}
I delay the adding of the keyListener to represent the time the user would take to press a button which would, in turn, activate the keyListener. I know the sleep is not the issue because in my large scale project I have the same issue but it is after I press a button after waiting x amount of time to load up the game space. I do not know if I am repainting and validating correctly but no one seems to have this issue. Any help would be appreciated. Thanks!