键侦听器未检测到键

时间:2013-05-20 07:59:07

标签: key listener keylistener

我的密钥监听器出现问题,根本没有检测到任何密钥。 我可能已经完成搞砸了或者希望只是遗漏了一些简单但我无法看到的东西。任何帮助将不胜感激

public class OpeningMenu extends JLayeredPane implements KeyListener{
JFrame OpeningMenu;
JLayeredPane layeredPane;
JPanel backgroundPanel, arrowPanel;

SnakeClient client;
Login login;
Register register;

ImageIcon backgroundImage, arrowImage;
JLabel backgroundLabel, arrowLabel;

String backgroundPath = "D:/Uni/Workspace/ClientTest/loginBackground.png";
String arrowPath = "D:/Uni/Workspace/ClientTest/arrow.png";

int option = 1;
int Xpos = 310;
int Ypos = 332;

public OpeningMenu(SnakeClient client)
{
    this.client = client;

    OpeningMenu = new JFrame("Opening Menu");
    OpeningMenu.setSize(1100,800);
    OpeningMenu.setLayout(new BorderLayout());
    OpeningMenu.setLocationRelativeTo(null);  // center the frame
    OpeningMenu.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 

    loadImages();
    createUI(); 
}

public void loadImages()
{
    backgroundImage = new ImageIcon(backgroundPath);
    arrowImage = new ImageIcon(arrowPath);

    backgroundLabel = new JLabel(backgroundImage);
    arrowLabel = new JLabel(arrowImage);
}

public void createUI()
{

    layeredPane = new JLayeredPane();
    layeredPane.setBounds(0, 0, 1100, 800);
    OpeningMenu.add(layeredPane);

    backgroundPanel = new JPanel();  
    backgroundPanel.setBounds(0,0,backgroundImage.getIconWidth() , backgroundImage.getIconHeight());     
    backgroundPanel.add(backgroundLabel);

    arrowPanel = new JPanel();
    arrowPanel.setBackground(Color.BLACK);
    arrowPanel.setBounds(Xpos, Ypos, arrowImage.getIconWidth() + 10,arrowImage.getIconHeight() + 10);
    arrowPanel.add(arrowLabel);

    layeredPane.add(backgroundPanel, new Integer(0),0);
    layeredPane.add(arrowPanel, new Integer(1),0);

    OpeningMenu.setEnabled(true);
    OpeningMenu.setVisible(true);
}// createUI()

public void keyTyped(KeyEvent e) 
{
    System.out.println("1"); 
}

@Override
public void keyPressed(KeyEvent e) 
{
    System.out.println("2"); 

    int keyCode = e.getKeyCode();

    if(keyCode == KeyEvent.VK_UP)
    {
      System.out.println("Up-Key"); 
    }

    if(keyCode == KeyEvent.VK_DOWN)
    {
        System.out.println("Down-Key"); 
    }
}

public void keyReleased(KeyEvent e) 
{
    System.out.println("3"); 
}

1 个答案:

答案 0 :(得分:1)

当您KeyListener没有收听时,您必须通过addKeyListener()将其明确附加到组件。