2016-07-11 79 views
-1

我創建了一個KeyListener,並且每當我按W(指定的鍵)時,就沒有打印出來,就像我告訴它的那樣。我已經嘗試過在堆棧交換和其他許多論壇上進行討論,以至於沒有結論。我的KeyListener不工作 - 爲什麼?

代碼:

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(); 
    } 
} 

回答

0

你可能需要到的KeyListener添加到您的JFrame在你的遊戲類。像這樣的想法。 frame.addKeyListener(this);

可能也需要這樣太: frame.setFocusable(true);

+0

謝謝你曾經這麼多! – Manders

+0

np。玩得開心做遊戲。 – TheRealFawby