简体   繁体   中英

Java KeyListener is not working, I think it has to do with addKeyListener(); method i am not sure why

I am working on a snake game that follows mvc frame work. For this I have decided that the keyListener will be in the controller section of the program. Originally I had it in the view section and it worked well. however when I moved KeyListener to the controller it did not work. I think is has something to do with the fact that view extends JFrame but Controller does not. my specific problem is that I do not know how to add addKeyListener(this). My goal in having the KeyListener is so that I know when the arrow keys are pressed for the game.

This is controller

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

//import static com.sun.java.accessibility.util.AWTEventMonitor.addKeyListener;// this is what was suggested so that addKeyListener would work

public class Controller implements KeyListener {//this talks to the model and view
Model model;
View view;
public Controller(){
    model=new Model();
    view=new View();
    addKeyListener(this);
    System.out.println("Hello");

}
@Override
public void keyTyped(KeyEvent e) {
    System.out.println("Hey");
}

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

}

@Override
public void keyReleased(KeyEvent e) {
    System.out.println("WRUD");
}

public static void main(String[] args){
    System.out.println("Welcome to Snake");
    new Controller();
}

}

This is view

import javax.swing.*;
import java.awt.*;

public class View extends JFrame  {//this is what is viewed
        GameBoard gameBoard;//=new GameBoard();
    protected View() {
    super();
    setTitle("Snake");
    setSize(500,500);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(new BorderLayout());
    gameBoard=new GameBoard();
    add(gameBoard);
    setVisible(true);
}

    // @Override
   // protected void paintComponent(Graphics g){
   //    super.paintComponent(g);
   //     g.setColor(Color.RED);
   //     g.drawRect(0,0,10,10);
   //     g.fillRect(0,0,10,10);
   // }


}

I really appreciate any help. If something is not clear or if i need to add more code I will gladly do it.

You can't call addKeyListener on your Controller class because it does not have a addKeyListener method.

You can implement KeyListener in your Controller and add it to your View instance. Just call addKeyListener on your view.

public Controller() {
    model = new Model();
    view = new View();
    view.addKeyListener(this); // changed
    System.out.println("Hello");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM