My KeyListener isn't working - why?

时间:2016-07-11 19:33:31

标签: java

I have created a KeyListener and whenever I press W (the specified key) nothing prints out like I told it to. I have tried looking around stack exchange and many other forums to come to no conclusion.

Code:

package com.software.manders;

import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class game implements KeyListener {
    //0 = English, 1 = Korean.
    public static int languageStatus = 0;
    public static int gameStatus = 0;
    static JFrame frame = new JFrame();

    public static void frameMaker() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setTitle("경기");
        frame.setSize(600, 600);

        new game();
    }

    public game() {
        if (gameStatus == 0) {
            JPanel p = new JPanel();
            JLabel lab1 = new JLabel();
            p.setLayout(new FlowLayout());
            p.add(lab1 = new JLabel("Please select a language : "));

            JLabel lab2 = new JLabel();
            p.add(lab2 = new JLabel("Press A for English"));

            JLabel lab3 = new JLabel();
            p.add(lab3 = new JLabel("Press B for Korean"));

            frame.add(p);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int id = e.getKeyCode();

        if (id == KeyEvent.VK_W) {
            System.out.println("W is pressed");
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int id = e.getKeyCode();

        if (id == KeyEvent.VK_W) {
            System.out.println("W is released");
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    public static void main(String[] args) {
        frameMaker();
    }
}

1 个答案:

答案 0 :(得分:0)

You probably need to add the keylistener to your JFrame in your Game class. Something like this I imagine. frame.addKeyListener(this);

Might also require this too: frame.setFocusable(true);