1

我的 Key Listener 有问题,它根本没有检测到任何键。我可能已经把它搞砸了,或者希望只是遗漏了一些简单的东西,但我就是看不到它。任何帮助,将不胜感激

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"); 
}
4

1 回答 1

1

在你KeyListener没有听的那一刻,你必须通过addKeyListener().

于 2013-05-20T08:07:37.647 回答