MrDrProfessorTyler
MrDrProfessorTyler

Reputation: 423

Java: Adding a keyListener to an already visible JFrame

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!

Upvotes: 1

Views: 2954

Answers (1)

wchargin
wchargin

Reputation: 16047

The issue is probably related to an error in your use of the focus subsystem.

In this StackOverflow question, David shows that although the panel is set up correctly,

... the panel isn't asking for focus. Try using myPanel.requestFocus();

In addition, the Java Tutorial on KeyListeners mentions that

key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys

(emphasis added).

So, instead of using add(new space()), you should:

space s = new space();
add(s);
s.requestFocus();

and that should fix your problem.

Upvotes: 2

Related Questions